diff --git a/src/corelib/global/qcompilerdetection.h b/src/corelib/global/qcompilerdetection.h index 5baa69270e5..d52722afb73 100644 --- a/src/corelib/global/qcompilerdetection.h +++ b/src/corelib/global/qcompilerdetection.h @@ -970,6 +970,15 @@ #define Q_DECL_ENUMERATOR_DEPRECATED Q_DECL_DEPRECATED #define Q_DECL_ENUMERATOR_DEPRECATED_X(x) Q_DECL_DEPRECATED_X(x) +// [[nodiscard]] constructor +#ifndef Q_NODISCARD_CTOR +# if __has_cpp_attribute(nodiscard) >= 201907L +# define Q_NODISCARD_CTOR [[nodiscard]] +# else +# define Q_NODISCARD_CTOR +# endif +#endif + /* * Fallback macros to certain compiler features */ diff --git a/src/corelib/thread/qmutex.h b/src/corelib/thread/qmutex.h index af77f556fd4..407473c799f 100644 --- a/src/corelib/thread/qmutex.h +++ b/src/corelib/thread/qmutex.h @@ -231,6 +231,7 @@ template class [[nodiscard]] QMutexLocker { public: + Q_NODISCARD_CTOR inline explicit QMutexLocker(Mutex *mutex) QT_MUTEX_LOCK_NOEXCEPT { m_mutex = mutex; @@ -240,6 +241,7 @@ public: } } + Q_NODISCARD_CTOR inline QMutexLocker(QMutexLocker &&other) noexcept : m_mutex(std::exchange(other.m_mutex, nullptr)), m_isLocked(std::exchange(other.m_isLocked, false)) @@ -326,6 +328,7 @@ template class [[nodiscard]] QMutexLocker { public: + Q_NODISCARD_CTOR inline explicit QMutexLocker(Mutex *) noexcept {} inline ~QMutexLocker() noexcept {} diff --git a/tests/auto/corelib/global/qglobal/tst_qglobal.cpp b/tests/auto/corelib/global/qglobal/tst_qglobal.cpp index 3f4e903a9a5..3d9759ff5bf 100644 --- a/tests/auto/corelib/global/qglobal/tst_qglobal.cpp +++ b/tests/auto/corelib/global/qglobal/tst_qglobal.cpp @@ -37,6 +37,7 @@ private slots: void qRoundDoubles(); void PRImacros(); void testqToUnderlying(); + void nodiscardConstructor(); }; extern "C" { // functions in qglobal.c @@ -691,5 +692,25 @@ void tst_QGlobal::testqToUnderlying() QCOMPARE(qToUnderlying(EE2), 456UL); } +void tst_QGlobal::nodiscardConstructor() +{ + // Syntax-only test, just to make sure that Q_NODISCARD_CTOR compiles + // on all platforms. + // Other code is just to silence all various compiler warnings about + // unused private members or methods. + class Test { + public: + Q_NODISCARD_CTOR explicit Test(int val) : m_val(val) {} + + int get() const { return m_val; } + + private: + int m_val; + }; + + Test t{42}; + QCOMPARE(t.get(), 42); +} + QTEST_APPLESS_MAIN(tst_QGlobal) #include "tst_qglobal.moc"