Qt Signals and Slots object disconnect?

2020-01-31 04:56发布

问题:

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.

回答1:

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



回答2:

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