diff --git a/src/kdbindings/connection_handle.h b/src/kdbindings/connection_handle.h index 57750be..2708e8a 100644 --- a/src/kdbindings/connection_handle.h +++ b/src/kdbindings/connection_handle.h @@ -180,6 +180,23 @@ class ConnectionHandle return false; } + /** + * This function exists to intentionally silence the [[nodiscard]] warning generated when connecting. + * + * In cases where you know for certain that the lifetime of the signal does not extend beyond the lifetime of the slot, you may not need the ConnectionHandle, so you can use release to discard it. + * + * Example: + * ```cpp + * bool called = false; + * { + * Signal mySignal; + * // The signal will not outlive the reference to the `called` bool, so it's fine to ignore the ConnectionHandle. + * mySignal.connect([&called](){ called = true; }).release(); + * } + * ``` + */ + void release() const { } + private: template friend class Signal; diff --git a/src/kdbindings/signal.h b/src/kdbindings/signal.h index ace595c..d0b1f04 100644 --- a/src/kdbindings/signal.h +++ b/src/kdbindings/signal.h @@ -355,7 +355,7 @@ class Signal * All connected functions should handle their own exceptions. * For backwards-compatibility, the slot function is not required to be noexcept. */ - ConnectionHandle connectReflective(std::function const &slot) + KDBINDINGS_WARN_UNUSED ConnectionHandle connectReflective(std::function const &slot) { ensureImpl(); diff --git a/tests/signal/tst_signal.cpp b/tests/signal/tst_signal.cpp index c551817..9a9e7d8 100644 --- a/tests/signal/tst_signal.cpp +++ b/tests/signal/tst_signal.cpp @@ -798,6 +798,16 @@ TEST_CASE("ConnectionHandle") REQUIRE_FALSE(handle.belongsTo(signal)); REQUIRE(handle.belongsTo(otherSignal)); } + + SUBCASE("A ConnectinHandle can be released to ignore the nodiscard warning") + { + bool called = false; + { + Signal mySignal; + // As long as this compiles without error, the test can pass, no need to REQUIRE anything + mySignal.connect([&called]() { called = true; }).release(); + } + } } TEST_CASE("ScopedConnection")