26

I am wondering if i need to disconnect singals and slots if i destroy the signal emitting object. Here is an example:

QAudioOutput * audioOutput = new QAudioOutput(format,mainWindow);
connect(audioOutput,SIGNAL(stateChanged(QAudio::State)),this,SLOT(stateChanged(QAudio::State)));

delete audioOutput;

audioOutput = new QAudioOutput(format,mainWindow);
connect(audioOutput,SIGNAL(stateChanged(QAudio::State)),this,SLOT(stateChanged(QAudio::State)));

Will this automatically disconnect the signal from the old audioOutput, or will it lead to mem leaks or some other undefined behavior ?

Thank you in advance.

Daenyth
  • 35,856
  • 13
  • 85
  • 124
Anton
  • 1,181
  • 2
  • 17
  • 27
  • Although `QObject`s safely clean up connections when they are destroyed I would recommend against deleting a `QObject` that has already had its parent set as you have above since this will short circuit the automatic mechanisms already in place for `QObject`s. It is also generally safer to use `deleteLater()` instead of deleting a `QObject` directly. – Arnold Spence Feb 13 '12 at 17:30

2 Answers2

40

The signals are automatically disconnected when you call the QObject destructor. Have a look at the Qt documentation: QObject Destructor

Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
Adrien BARRAL
  • 3,474
  • 1
  • 25
  • 37
4

You don't have to manually disconnect() signals and slots, the QObject destruction cleans them up automatically.

AAEM
  • 1,837
  • 2
  • 18
  • 26
Frank Osterfeld
  • 24,815
  • 5
  • 58
  • 70