PDA

View Full Version : problem with QWeakPointer, correct usage of smart poiners ?



pospiech
9th May 2011, 13:03
I have classes, corresponding to devices connected to a controller, which are saved
in a vector in the controller class.

I want to have full control over the devices within the controller, which means they must not be copied and shall not be deleted.

The base class controller saves pointers to base class devices. With real controllers (derived) and real devices (derived) it saves pointers to derived device classes - that is why I want to use pointers.

My idea was to use QSharedPointer and QWeakPoiner. Basically I want to know if this is the right idea, and why my code fails.

The devices (CommonPositioningStage) are stored in the CommonPositioningController-class (the base class)


class CommonPositioningControllerPrivate
{
public:
CommonPositioningControllerPrivate()
{
// automatically delete all instances of
// CommonPositioningStage
stageProperties.clear();
}
QVector<QSharedPointer<CommonPositioningStage> > stageProperties;
};

CommonPositioningController::CommonPositioningCont roller()
: d(new CommonPositioningControllerPrivate)
{
}

...
bool CommonPositioningController::addStage(CommonPositi oningStage * newStage)
{
if (newStage == 0) return false;

// check if axis does not exist yet
...
// add only if axis does not exist
if (!axisAlreadyExists) {
d->stageProperties.push_back(
QSharedPointer<CommonPositioningStage>(newStage));
}
return !axisAlreadyExists;
}

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


Usage in derived Controller class


void QMicosPolluxController::setDevice(int axis, QMicosPolluxDevice * device)
{
if (device) {
addStage(device);
}
}


Usage in ui classes


class WidgetMicosPolluxControllerMove : public QWidget
...
private:
QMicosPolluxController * m_controller;
QWeakPointer<QMicosPolluxDevice> m_device;
...
};

void WidgetMicosPolluxControllerMove::setController(QMi cosPolluxController * parentController)
{
m_controller = parentController;
if (m_controller->stageCount() > 0) {
m_device = m_controller->stage();
}
}


However acces to m_device fails, because non of the class functions are available



m_device.limitPosition()




WidgetMicosPolluxControllerMove.cpp:127: error: 'class QWeakPointer<QMicosPolluxDevice>' has no member named 'limitPosition'


Now how do I access the QMicosPolluxDevice class in QWeakPointer and is the whole appreach correct?

The only other way i can think of is using plain pointers. It is dangerous, but causes no problems on compilation.

nightghost
9th May 2011, 14:16
Try:

m_device.data()->limitPosition()

The QWeakPointer has no overloaded dereferencing operator like QSharedPointer::operator->