QSharedPointer: already has reference counting!



  • Hello.

    So I have a code like this, which works perfectly fine:
    @void ParentDialog::foobar(void)
    {
    ChildDialog *child = new ChildDialog(this);
    child->exec();
    delete child;
    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:
    @void ParentDialog::foobar(void)
    {
    QSharedPointer<ChildDialog> child(new ChildDialog(this));
    child->exec();
    }@

    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:
    @void ParentDialog::foobar(void)
    {
    std::unique_ptr<ChildDialog> child(new ChildDialog(this));
    child->exec();
    }@

    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.

    Thanks!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.