[Qt-interest] correct usage of qt smart pointers ?

Matthias Pospiech matthias.pospiech at gmx.de
Mon May 9 13:50:11 CEST 2011


I want to store derived classes pointer in a base class vector.
The saved pointer shall be accesible, but not deletable from outside

I was thinking that QSharedPointer is the right tool for that:

QVector<QSharedPointer<CommonPositioningStage> > stageProperties;

which are added and accessed with

bool CommonPositioningController::addStage(CommonPositioningStage * 
newStage)
{
...
     if (!axisAlreadyExists) {
         d->stageProperties.push_back(
                     QSharedPointer<CommonPositioningStage>(newStage));
     }
     return !axisAlreadyExists;
}

QSharedPointer<CommonPositioningStage> CommonPositioningController::stage()
{
     return d->stageProperties[m_currentListIndex];
}

However in this case I can not copy them as real pointers, and to copy 
them as
QWeakPointers is not really helpfull (I do not seem to understand the 
usage of QWeakPointer anyway,
unfortunatley to docs contain not example.)

QWeakPointer<QMicosPolluxDevice> m_device;
m_device = m_controller->stage();

fails because QWeakPointer does not contain stage().

Any hints how one would implement this?

The alternative would be not to save pointers, but objects of 
CommonPositioningStage
and imply that externaly nothing can be changed.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20110509/08a78380/attachment.html 


More information about the Qt-interest-old mailing list