Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion rclcpp_async/include/rclcpp_async/co_context.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -174,10 +174,14 @@ class CoContext : public Executor
return task;
}

// The callable is moved into the task's frame: a lambda's captures must
// outlive the caller's full-expression, as the task resumes after it.
template <typename CallbackT>
[[nodiscard]] auto create_task(CallbackT && callback)
{
return create_task(callback());
return create_task([](std::decay_t<CallbackT> cb) -> decltype(cb()) {
co_return co_await cb();
}(std::forward<CallbackT>(callback)));
}

// --- Awaiter factory methods ---
Expand Down
19 changes: 19 additions & 0 deletions rclcpp_async/test/test_sleep.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -196,3 +196,22 @@ TEST_F(SleepTest, AwaitCreateTaskAlreadyDone)
ASSERT_TRUE(task.handle.done());
EXPECT_EQ(result, 99);
}

TEST_F(SleepTest, CreateTaskKeepsTheLambdaAlive)
{
auto captured = std::make_shared<int>(42);
auto task = ctx_->create_task([this, captured]() -> Task<int> {
co_await ctx_->sleep(10ms);
co_return *captured;
});
// The lambda is a temporary of the statement above, yet still in use.
ASSERT_EQ(captured.use_count(), 2);

auto deadline = std::chrono::steady_clock::now() + 5s;
while (!task.handle.done() && std::chrono::steady_clock::now() < deadline) {
executor_.spin_some();
std::this_thread::sleep_for(1ms);
}
ASSERT_TRUE(task.handle.done());
EXPECT_EQ(task.result(), 42);
}
Loading