【发布时间】:2020-02-18 12:36:33
【问题描述】:
我有一个函数,它使用 std::queue's 内置 emplace 将 lambda 排入队列。我创建了shared_ptr 对象(任务),稍后我将在 lambda 中捕获它。
template<typename Func, typename... Args>
auto submit(Func&& f, Args&&... args)
{
using result_type = std::result_of_t<Func(Args...)>;
using pckg_task_type = std::packaged_task<result_type()>;
auto task = std::make_shared< pckg_task_type >(
std::bind(std::forward<Func>(f), std::forward<Args>(args)...) );
...
}
这是造成混乱的部分:
案例 1:完美运行
tasks.emplace(
[task](){
auto wptr = std::weak_ptr<pckg_task_type>(task);
if( auto p = wptr.lock() )
{
(*p)();
}
else
throw std::runtime_error("weak error");
}
);
案例2:立即抛出异常
tasks.emplace(
[wc = std::weak_ptr<pckg_task_type>(task)](){
if( auto p = wc.lock() )
{
(*p)();
}
else
throw std::runtime_error("weak error");
}
);
任务定义为
std::queue< std::function<void()> > tasks;
从案例 2 调用 lambda 而不将其放入队列不会引发异常。
谁能解释上述案例之间的区别?问题出在哪里?
【问题讨论】:
标签: c++ lambda capture weak-ptr emplace