c++ - lambda 函数中的 std::unique_ptr 导致段错误

标签 c++ c++11 lambda segmentation-fault unique-ptr

我有以下代码:

#include <functional>
#include <memory>
#include <string>
#include <iostream>

struct A{
    int i = 5;
};


class B{
    std::unique_ptr<A> a;
    std::function<void (void)> f;

    public:
    B(std::unique_ptr<A> a) 
        : a(std::move(a)), 
        f([&](){
                std::cout << a->i << '\n'; //segfaults when executing a->i
                })
    {}

    B()
        : a(new A),
        f([&](){
                std::cout << a->i << '\n'; //works fine 
                })
    {}

    void execLambda(){
        f();
    }

    void exec(){
       std::cout << a->i << '\n'; //works fine 
    }
};

int main(){

    B b1;
    b1.exec(); //works fine
    b1.execLambda(); //works fine

    B b2(std::unique_ptr<A>(new A));
    b2.exec(); //works fine
    b2.execLambda(); //will segfault
    return 0;

}

似乎当一个对象声明对现有 unique_ptr 的所有权并在 lambda 中使用该 unique_ptr 时,就会发生段错误。为什么在这种特定情况下会发生段错误?无论如何在所有权已转移的 lambda 中使用 unique_ptr 吗?

非常感谢!

最佳答案

不要将成员和方法参数命名为同一事物。但是,如果您坚持这样做,您应该能够将 lambda 捕获更改为 [this] 而不是 [&] 以解决问题。

正如评论者所说:

At a guess I'd say the lambda is capturing the a from the constructor - the one you move from - not the one inside the class. – Jonathan Potter

关于c++ - lambda 函数中的 std::unique_ptr 导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18751178/

相关文章:

python - pandas dataframe 应用 lambda if else erro

lambda - 如何在 C++ 仿函数中传递 lambda 函数?

c++ - T& 对于某些模板参数 T 意味着什么?

c++ - 如何在 C++ 中使用不同的参数多次调用一个函数

c++ - 检查一组类型是否是另一组类型的子集

c++ - 将右值分配给 'const auto&' 时会发生什么

c# - 已编译的 lambda 表达式用作属性 getter 和 setter : wrong benchmarking method or wrong lambda expression construction?

c++ - 模板定义中的空尖括号

c++ - 从 C++ 类模板中的函数调用另一个成员函数

linux下的c++ flash