我有学费。
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;
};
和存储费用映射的类 FeeList
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 的构造函数具有以下代码行,这些代码行通过 lambdas 填充“get_description” vector
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 的链接,其中粘贴了我的代码并解决了提到的问题(整数值;和字符串代码;是好的字符串描述;是空的)http://coliru.stacked-crooked.com/a/bc56eb53400bd1af 也可以使用 Coliru 命令行找到此文件:cat/Archive2/bc/56eb53400bd1af/main.cpp
最佳答案
隐式实例化的 Fee
移动构造函数复制了 get_description
中的 lambda - 但它没有到达那些 lambda 内部并更新它们捕获的指针。它们仍然指向原始的 Fee
对象,该对象已被移走。然后,您的程序会通过访问移出的对象来表现出未指定的行为。
与其拥有两个单独的字符串变量和一个 lambda vector ,不如拥有一个字符串 vector ?
关于c++ - Lambda 返回空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58135056/