我有以下代码:
#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/