QSharedPointer through signals / slots
-
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.
-
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.