[Development] HEADS UP: do not pass const objects to QObject::disconnect(const QMetaObject::Connection&)!
Thiago Macieira
thiago.macieira at intel.com
Thu Mar 26 21:39:09 CET 2026
On Thursday, 26 March 2026 11:41:38 Pacific Daylight Time Marc Mutz via
Development wrote:
> If you pass const objects _originally marked as const_ (e.g. the key of a
> std::map, or an object you declared const yourself:
>
> const auto c = QObject::connect(~~~~);
> ~~~~
> QObject::disconnect(c); // UB!!
>
> Then you need to take action: make the Connection object _not_ originally
> const.
By "need", understand "at your convenience". This is UB, but we have not found
any compiler that uses this to optimise things nor do we expect that to happen
soon. So if your code appears to works in spite of the UB, there's no reason
to suspect it's actually broken.
If you are upgrading your compilers, I agree with Marc: apply the trivial fix.
> In the case above, do
>
> auto c = QObject::connect(~~~~); // NOT const!
>
> if you don't control the declaration (e.g. its a key in a std::map), then DO
> NOT CALL disconnect() on it. Take a copy and call disconnect() on that:
>
> const c = QObject::connect(~~~~); // can't change this even if I tried
> ~~~~
> auto copy = c; // take a copy
> QObject::disconnect(copy); // and only disconnect() the copy
Anyone reading this is going to ask why we can't apply this fix ourselves, by
taking a copy.
The point is not whether we disconnect or not. As Marc said:
> The connection will be disconnected either way, it suffices if any of the
> copies of the Connection gets passed to disconnect()
The discussion is on how early we can free memory.
> Patch your code, and pick to all your branches.
At least to ones where you may compile with future compiler versions. If
you're locked to a particular compiler, see above.
> Sorry for the annoyance, and for failing to detect the issue sooner, but
> this is really only fixable at the user side.
The code has been around since 2012. If in 14 years no one had noticed the
problem, no compiler was taking advantage of the UB to optimise.
--
Thiago Macieira - thiago.macieira (AT) intel.com
Principal Engineer - Intel DCG - Platform & Sys. Eng.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 5150 bytes
Desc: not available
URL: <http://lists.qt-project.org/pipermail/development/attachments/20260326/a5583c6f/attachment-0001.bin>
More information about the Development
mailing list