C++ std::lambda函数中唯一的_ptr导致分段错误
我有以下代码:C++ std::lambda函数中唯一的_ptr导致分段错误,c++,c++11,lambda,segmentation-fault,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::uniq
#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;
}
#包括
#包括
#包括
#包括
结构A{
int i=5;
};
B类{
std::唯一的ptr a;
std::函数f;
公众:
B(标准::唯一性a)
:a(std::move(a)),
f([&](){
我可以吗
})
{}
B()
:a(新的a),
f([&](){
std::cout i不能为成员和方法参数命名相同的名称。但是,如果您坚持这样做,您应该能够将lambda捕获更改为[this]
,而不是[&]
,以解决此问题
正如一位评论人士所说:
我猜lambda是从构造函数中捕获a的
-你离开的那个,而不是班里的那个。——乔纳森·波特
我猜lambda是从构造器中捕获a
,你从中移动的构造器,而不是类中的构造器。不要给所有的东西取相同的名字?:-)Jonathan说的,它是指定的behaviour@Jonathan当前位置就是这样!我不敢相信我竟然没有意识到这一点。非常感谢!