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 through signals / slots
Forum Updated to NodeBB v4.3 + New Features

QSharedPointer through signals / slots

Scheduled Pinned Locked Moved General and Desktop
2 Posts 2 Posters 2.1k 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.
  • V Offline
    V Offline
    vezprog
    wrote on last edited by
    #1

    I have a question about using smart pointers with signals and slots. When you pass a QSharedPointer into a signal / slot connection, does the object get copied (would the reference count be incremented?). I started using a normal pointer, but I ran into issues with the object getting connected to multiple slots and had to use my own reference count for deletion...I know QSharedPointers should only be created from other QSharedPointers to keep the reference count valid.

    Here is an example:
    @
    // sender class
    class A : public QObject
    {
    Q_OBJECT
    public:
    void test()
    {
    QSharedPointer<Data> dataPtr = QSharePointer<Data>(new Data());
    emit pushData(dataPtr);
    }

     signals:
          void pushData(QSharedPointer<Data> object);
    

    }

    // receiver class
    class B : public QObject
    {
    Q_OBJECT
    slots:
    void receiveData(QSharedPointer<Data> object)
    {
    // access data here
    // does the pointer delete when it goes out of scope at the end of this function?
    }
    }

    int main()
    {
    ...
    A a;
    B b;
    // should register metadata type for slot
    connect(a, SIGNAL(pushData(QSharedPointer<Data>), b, SLOT(receiveData(QSharedPointer<Data>)));
    ....
    }
    @

    I know the QSharedPointer object gets deleted once the function goes out of scope in the test function() which would decrement the reference count, but would the QSharedPointer still be valid in the slot?

    I am trying to wrap my head around smart pointers. Thanks.

    1 Reply Last reply
    0
    • A Offline
      A Offline
      andreyc
      wrote on last edited by
      #2

      I personally do not use smart pointers in the signal/slot communication so I don't know it.
      You already have a test to answer your question.
      Add a debug output to the destructor of Data to see when it gets deleted.
      Add debug output to test() function before and after emit
      Add debug output receiveData() function.

      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