Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. QSharedPointer: already has reference counting!

QSharedPointer: already has reference counting!

Scheduled Pinned Locked Moved General and Desktop
1 Posts 1 Posters 2.5k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Offline
    M Offline
    MuldeR
    wrote on last edited by
    #1

    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!

    My OpenSource software at: http://muldersoft.com/

    Qt v4.8.6 MSVC 2013, static/shared: http://goo.gl/BXqhrS

    Go visit the coop: http://youtu.be/Jay...

    1 Reply Last reply
    0

    • Login

    • Login or register to search.
    • First post
      Last post
    0
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Get Qt Extensions
    • Unsolved