c++ - 将共享指针存储在 lambda 中以使其保持事件状态

标签 c++ c++11 lambda shared-ptr functor

这样的结构旨在存储在 lambda 中:

struct MyStruct {
  void testfunction() {
    // Do something
  }
};

我想要的是从中构造一个共享指针并将该指针存储在 lambda 中:

auto ptr = std::make_shared<MyStruct>();
std::function<void()> caller = [ptr](){
  ptr->testFunction();
}

调用者对象被赋予一个函数,并被该函数复制。 ptr 对象超出范围。当我传递调用者对象时,共享指针是否仍然存在?

是否保证 ptr 存储在 lambda 中,并且只要调用者存在或被返回,对象就由该指针管理?如果我不调用 testFunction,是否有任何编译器优化?

此问题特定于 boost::asio 问题,我想通过异步处理程序传递一些对象。

最佳答案

来自 cppreference

If the lambda-expression captures anything by copy (either implicitly with capture clause [=] or explicitly with a capture that does not include the character &, e.g. [a, b, c]), the closure type includes unnamed non-static data members, declared in unspecified order, that hold copies of all entities that were so captured.

所以,按照as-if rule ,预计您的编译器将生成代码,如果您确实拥有此拷贝,那么该代码的行为将保持事件状态。

关于c++ - 将共享指针存储在 lambda 中以使其保持事件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48782143/

相关文章:

c++ - "two-graph"中更改次数有限的最短路径

c++ - 关于 C++0x,我需要了解什么?

java - 使用 Lambda 将列表分组并汇总到 map 中

c# - 是否可以使用 C++ 解密在 Silverlight 中加密的数据?

c++ - 如何使用非类型模板参数和类型模板参数的混合来对函数进行模板化?

c++ - 在表达式 bool << integer 中,bool 是提升为 int,还是提升为与整数相同的类型?

c++ - 没有 'rvalue references to *this' 功能的解决方法

linux - 调试 "corrupted double-linked list"崩溃的最佳方法

c# - 如何通过 lambda 从列表中获取一种类型的 child ?

java动态判断当前执行的类