Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
QSharedPointer: already has reference counting!
MuldeR last edited by
So I have a code like this, which works perfectly fine:
ChildDialog *child = new ChildDialog(this);
child = NULL;
Both, ParentDialog and ChildDialog, are derived from QDialog, if that matters.
Now I though I can refactor this code using QSharedPointer class to get rid of the explicit delete, which looks like this and compiles fine:
QSharedPointer<ChildDialog> child(new ChildDialog(this));
This should delete the ChildDialog object automatically, when the QSharedPointer goes out of scope, since we have not copied the shared pointer anywhere!
bq. QSharedPointer will delete the pointer it is holding when it goes out of scope, provided no other QSharedPointer objects are referencing it.
But, instead, I get this error:
bq. QSharedPointer: pointer 0x489d60 already has reference counting
Can anybody explain why this happens ???
How can it already have "reference counting", when it just has been created freshly?
I though QSharedPointer was intended to work with objects derived from QObject...
Using a C++11 std::unique_ptr works fine, by the way:
std::unique_ptr<ChildDialog> child(new ChildDialog(this));
BTW: I know that std::unique_ptr does not do the same as QSharedPointer, because the latter does reference counting. However, since, in this example, the reference count is exactly 1, it doesn't make a difference. An Qt doesn't have QUniquePointer, AFAIK.