0

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. 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?

Thank you very much!

4

1 回答 1

1

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

正如评论者所说:

猜测一下,我会说 lambda 正在从构造函数中捕获 a - 你从中移动的那个 - 而不是类中的那个。——乔纳森·波特

于 2013-09-11T21:06:55.510 回答