为什么要在 lambda 的 cpp 中捕获此内容并获取对数据成员的引用导致段错误?

问题描述 投票:0回答:1
#include <functional>
#include <string>
#include <iostream>



struct Info
{
    std::string a{"abc"};
};


struct Handlers
{
    std::function<const Info&()> get_info;
};

class A
{
    public:
    A()
    {
        handler_ = Handlers{
            .get_info = [this](){return data;}
        };
    };


    Info data;
    Handlers handler_;
};

int main()
{
    A a;
    std::string k = a.handler_.get_info().a;
    std::cout << k;
}

上面的代码出现段错误

std::string k = a.handler_.get_info().a;

经过进一步调查,我发现

std::cout << &a.handler_.get_info();
打印
0

我使用以下版本的 g++

g++ (Ubuntu 12.2.0-3ubuntu1) 12.2.0
Copyright (C) 2022 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

我用以下命令编译文件

g++  main.cpp --std=c++2a
c++ segmentation-fault
1个回答
0
投票

问题是 lambda 按值返回,而您希望返回引用,请更改为

[this]() -> Info& {return data;}
© www.soinside.com 2019 - 2024. All rights reserved.