簡體   English   中英

lambda函數中的std :: unique_ptr導致分段錯誤

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

我有以下代碼:

#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]而不是[&]來解決問題。

正如評論員所說:

猜想我會說lambda是從構造函數中捕獲a的-您從中構造的a-而不是類內部的a。 –喬納森·波特

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM