Frage

Is it possible to use QPointer with QHash?

QPointer<QHash<QString, QPointer<QStringList>> >  pHash;
War es hilfreich?

Lösung

QPointer can only be used with QObject subclasses. Thus it cannot be used with QHash or QStringList, as both aren't QObject's. If the code above compiles for you, that's probably because you don't use pHash yet? Even initializing such a QPointer, e.g.

QPointer<QHash<QString, QString> > foo( new QHash<QString, QString>() );

gives errors like the following one (gcc):

error: cannot convert ‘QHash<QString, QString>*’ to ‘QObject*’ in initialization

If you really need (smart) pointers to containers, try QSharedPointer, which doesn't require the contained object to be of any specific type. Usually one creates containers on the stack though, creating them on the heap is unidiomatic and unnecessary in almost all cases. Qt's containers are implicitly shared, thus copying them is cheap.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top