简体   繁体   English

lambda函数中的std :: unique_ptr导致分段错误

[英]std::unique_ptr in lambda function causing segmentation fault

I have the following code: 我有以下代码:

#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;

}

It seems when an object claims ownership of an existing unique_ptr and uses that unique_ptr in a lambda, a segmentation fault occurs. 似乎当一个对象声明对现有unique_ptr的所有权并在lambda中使用该unique_ptr时,就会发生分段错误。 Why does a segmentation fault occur in this specific case? 为什么在这种特定情况下会发生分段错误? Is there anyway to use a unique_ptr in a lambda where ownership has been transferred? 无论如何,在所有权已转让的Lambda中使用unique_ptr?

Thank you very much! 非常感谢你!

Don't name members and method arguments the same thing. 不要将成员和方法参数命名为同一对象。 However, if you insist on doing so, you should be able to change your lambda capture to [this] instead of [&] to fix the problem. 但是,如果您坚持要这样做,则应该可以将lambda捕获更改为[this]而不是[&]来解决问题。

As a commenter said: 正如评论员所说:

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. 猜想我会说lambda是从构造函数中捕获a的-您从中构造的a-而不是类内部的a。 – Jonathan Potter –乔纳森·波特

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM