Lambda 返回空字符串

Lambda returns empty string

本文关键字:字符串 返回 Lambda      更新时间:2023-10-16

我有课费。

class Fee
{
private:
std::string _code;
int _value;
std::string _description_EN;
std::string _description_UA;
std::vector<std::function<std::string()>> get_description;
public:
//CONSTRUCTORS
Fee(int value, std::string_view code, std::string_view description_EN, std::string_view description_UA);
Fee(const std::string _csv_line, const char separator);
Fee(const Fee &) = delete;
Fee(Fee &&) = default;
//OPERATORS
Fee &operator=(const Fee &) = delete;
Fee &operator=(Fee &&) = default;
Fee &operator++() = delete;
Fee &operator++(int) = delete;
Fee &operator--() = delete;
Fee &operator--(int) = delete;
Fee &operator+(const Fee &other) = delete;
Fee &operator-(const Fee &other) = delete;
Fee &operator+=(const Fee &other) = delete;
Fee &operator-=(const Fee &other) = delete;
Fee &operator/(const Fee &other) = delete;
Fee &operator*(const Fee &other) = delete;
Fee &operator/=(const Fee &other) = delete;
Fee &operator*=(const Fee &other) = delete;
Fee &operator%(const Fee &other) = delete;
Fee &operator%=(const Fee &other) = delete;
//SETTERS
void set_new_value(int value);
//GETTERS
std::string code();
int value();
std::string description(Language language = Language::EN);
//FUNCTIONS
//DESTRUCTOR
~Fee() = default;
};

和存储费用地图的类费用清单

class FeeList
{
private:
std::map<std::string, Fee> _fee_list;
FeeList() = default;
public:
static FeeList &fee_list();
//CONSTRUCTORS
FeeList(const FeeList &) = delete;
FeeList(FeeList &&) = delete;
//OPERATORS
FeeList &operator=(const FeeList &) = delete;
FeeList &operator=(FeeList &&) = delete;
//SETTERS
//GETTERS
Fee &fee(const std::string &code);
//FUNCTIONS
void addFee(Fee &fee);
void from_csv_file(const std::string &inv_file, const std::string &um_file, const std::string &id_file, const std::string &tr_file, const char separator);
//DESTRUCTOR
~FeeList() = default;
};

类 Fee 的构造函数具有以下代码行,这些代码行通过 lambda 填充 "get_description" 向量

get_description.resize(2);
get_description[static_cast<size_t>(fee::Language::EN)] = [this]()->std::string{return _description_EN;};
get_description[static_cast<size_t>(fee::Language::UA)] = [this]()->std::string{return _description_UA;};

这些 lambda 由函数 "description(fee::Language::)" 调用,该函数应返回描述不适当的语言。 实施非常简单

std::string fee::Fee::description(Language language)
{
return get_description[static_cast<size_t>(language)]();
}

问题是空字符串是从 lambda 返回的。 我创建了简单的类来测试这种方法,它按预期工作。我无法弄清楚是问题所在。我正在获取其他变量(代码和值(的值,因此对象已正确存储。

编辑:这是一个链接,指向 coliru.stacked-crooked.com 粘贴我的代码并处理提到的问题(int值;和字符串代码;是Ok字符串描述;为空(http://coliru.stacked-crooked.com/a/bc56eb53400bd1af 这个文件也可以使用Coliru命令行找到:cat/Archive2/bc/56eb53400bd1af/main.cpp

隐式实例化的Fee将构造函数副本移动到get_description中的 lambda 上 - 但它不会到达这些 lambda 内部并更新它们捕获的指针。它们仍然指向已移动的原始Fee对象。然后,程序通过访问移自对象来展示未指定的行为。

与其有两个单独的字符串变量和一个 lambda 向量,为什么不只有一个字符串向量呢?