From c578d9943afd4478d9bf813067b002f2679df1d4 Mon Sep 17 00:00:00 2001 From: Giuseppe D'Angelo Date: Sat, 18 Sep 2021 11:29:23 +0200 Subject: [PATCH] Plaster [[nodiscard]] on some RAII classes The idea is to prevent silly mistakes such as QMutexLocker(mutex); doSomething(); where the locker is constructed and destroyed immediately. Compilers don't normally warn in these cases (as the constructor/destructor pairs involved do have side effects), but we can mark the type as [[nodiscard]] to encourage warnings. There is another couple of classes for which this would make sense (notably, the R/W lockers), but unfortunately those are exported classes, and GCC has a bug where one can't mix two different attribute syntaxes on the same entity [1], so I'm skipping those. [1] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102399 Change-Id: I75a2443dc71e6b80613b8edd52a04d3379355728 Reviewed-by: Qt CI Bot Reviewed-by: Volker Hilsheimer --- src/corelib/thread/qmutex.h | 4 ++-- src/corelib/tools/qscopedpointer.h | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/corelib/thread/qmutex.h b/src/corelib/thread/qmutex.h index 3e861ca0cb2..19463da6198 100644 --- a/src/corelib/thread/qmutex.h +++ b/src/corelib/thread/qmutex.h @@ -235,7 +235,7 @@ public: }; template -class QMutexLocker +class [[nodiscard]] QMutexLocker { public: inline explicit QMutexLocker(Mutex *mutex) QT_MUTEX_LOCK_NOEXCEPT @@ -313,7 +313,7 @@ private: class QRecursiveMutex : public QMutex {}; template -class QMutexLocker +class [[nodiscard]] QMutexLocker { public: inline explicit QMutexLocker(Mutex *) noexcept {} diff --git a/src/corelib/tools/qscopedpointer.h b/src/corelib/tools/qscopedpointer.h index 5c72e7415df..43e0718699c 100644 --- a/src/corelib/tools/qscopedpointer.h +++ b/src/corelib/tools/qscopedpointer.h @@ -103,7 +103,7 @@ typedef QScopedPointerObjectDeleteLater QScopedPointerDeleteLater; #endif template > -class QScopedPointer +class [[nodiscard]] QScopedPointer { public: explicit QScopedPointer(T *p = nullptr) noexcept : d(p) @@ -223,7 +223,7 @@ private: }; template > -class QScopedArrayPointer : public QScopedPointer +class [[nodiscard]] QScopedArrayPointer : public QScopedPointer { template using if_same_type = typename std::enable_if::type, Ptr>::value, bool>::type;