Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Here, my signal declaration:

signals:
    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 than one slot which is connected to the signal? Memory Leak or Dangling Pointer

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

What are your best practices?

like image 297
metdos Avatar asked Jul 06 '10 05:07

metdos


People also ask

How does signal connect to signal in Qt?

To connect the signal to the slot, we use QObject::connect(). There are several ways to connect signal and slots. The first is to use function pointers: connect(sender, &QObject::destroyed, this, &MyObject::objectDestroyed);

What is QObject in Qt?

QObject is the heart of the Qt Object Model. The central feature in this model is a very powerful mechanism for seamless object communication called signals and slots. You can connect a signal to a slot with connect() and destroy the connection with disconnect().

What is Q_emit?

Q_EMIT is simply a synonym for emit . This is useful when you're combining Qt code with other C++ code that also contains the identifier emit .


1 Answers

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.

like image 103
Ando Avatar answered Nov 13 '22 19:11

Ando