metdos metdos - 2 months ago 12
C++ Question

Deletion of objects send by signals, Ownership of objects in signals, Qt

Here, my signal declaration:

void mySignal(MyClass *);

And how I'm using it:

MyClass *myObject=new myClass();
emit mySignal(myObject);

Here comes my problem: Who is responsible for deletion of myObject:

1-)Sender code, what if it deletes before myObject is used? Dangling Pointer

2-)The slot connected to signal, what if there is no slot or more then one slot which are connected to the signal? Memory Leak or Dangling Pointer

How does Qt manage this sitution in its build-in signals? Does it use internal reference counting?

What are your best practices?


You can connect a signal with as many slots as you want so you should make sure that none of those slots are able to do something you would not want them to do with your object:

  • if you decide to pass a pointer as a parameter then you will be running in the issues you describe, memory management - here nobody can to the work for you as you will have to establish a policy for dealing with allocation/deletion. To some ideas on how to address this see the Memory Management Rules in the COM world.
  • if you decide to pass a parameter as a reference then you don't have to worry about memory management but only about slots modifying your object in unexpected ways. The ideea is not to pass pointers unless you have to - instead use references if you can.
  • if you decide to pass a const reference then, depending on your connection type, QT will pass the value of the object for you (see this for some details)
  • avoid any problems and pass by value :)

See also this question for some thoughts about passing pointers in signals.