[Development] HEADS UP: do not pass const objects to QObject::disconnect(const QMetaObject::Connection&)!
Thiago Macieira
thiago.macieira at intel.com
Fri Mar 27 14:08:29 CET 2026
On Thursday, 26 March 2026 21:16:26 Eastern Daylight Time Giuseppe D'Angelo
via Development wrote:
> * therefore, compilers do NOT normally see both the const_cast mutating
> the object and original object declared as const, detect UB, and do evil
> things based on the presence of UB. LTO or similar technology would be
> necessary for the compiler to even be able to do this kind of reasoning.
> This firewalling alone reduces the possibility of things going horribly
> wrong to infinitesimally small quantities.
While I agree with everything else you wrote, there is a possibility for UB in
inline code: the move constructor, move-assignment operator, and swap()
Connection(Connection &&other) noexcept : d_ptr(std::exchange(other.d_ptr,
nullptr)) {}
QT_MOVE_ASSIGNMENT_OPERATOR_IMPL_VIA_PURE_SWAP(Connection)
void swap(Connection &other) noexcept { qt_ptr_swap(d_ptr, other.d_ptr); }
The compiler is *allowed* to assume that d_ptr did not change after the call
to disconnect() and thus cache it outside of the object itself. So if you did
disconnect() and then swap or move, the compiler could re-materialise the
pointer which is now dangling. When the destructor is then called, this could
crash.
In practice, like you said, this does not happen. Compilers do not appear to
optimise based on the constness of the object. I've shown so experimentally
and you've found bug reports asking that this optimisation be added.
> * but even without firewalling, no optimizing compiler we support today
> detects or exploits UBs in const_cast; even when they're "blatant". If
> the Big Three don't optimize on this I reject the notion that "some
> other compiler out there might do it". "Some other compiler we don't
> know about (and therefore DO NOT support)" isn't a starting point.
If they did exist, we'd probably be aware of this bug through bug reports. And
the worst case scenario would be no different than any other bug: upgrade Qt to
get a fixed version.
--
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/20260327/a4a833ef/attachment-0001.bin>
More information about the Development
mailing list