#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
问题是 lambda 按值返回,而您希望返回引用,请更改为
[this]() -> Info& {return data;}