Skip to content

Commit

Permalink
feat: ConnectionHandle::release to ignore warning
Browse files Browse the repository at this point in the history
As described in #43, you now get a warning if you don't use the
ConnectionHandle that is returned by connecting to a signal.
But as @lemirep noted, this can be annoying without a proper way to
silence the warning.
This commit adds a `release` function that can simply be used to ignore
the nodiscard warning intentionally.

Fix #43
  • Loading branch information
LeonMatthesKDAB committed Aug 26, 2024
1 parent d21bc12 commit 076eeed
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
17 changes: 17 additions & 0 deletions src/kdbindings/connection_handle.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<int> 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<typename...>
friend class Signal;
Expand Down
2 changes: 1 addition & 1 deletion src/kdbindings/signal.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<void(ConnectionHandle &, Args...)> const &slot)
KDBINDINGS_WARN_UNUSED ConnectionHandle connectReflective(std::function<void(ConnectionHandle &, Args...)> const &slot)
{
ensureImpl();

Expand Down
10 changes: 10 additions & 0 deletions tests/signal/tst_signal.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<int> 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")
Expand Down

0 comments on commit 076eeed

Please sign in to comment.