0

我收到一个错误:
错误:从“std::basic_string”类型的右值对“std::string& {aka std::basic_string&}”类型的非常量引用无效初始化

代码是:

 const std::string& hitVarNameConst = (isKO ? "isKO" : "isKI");
 for (int i = 0; i < numAssets; i++){
      std::string& hitVarName1 = hitVarNameConst + Format::toString(i + 1);
      //use hitVarname1 with some other function
      }

如何消除此错误?早些时候我尝试了以下代码,它仍然抛出相同的错误:

    for (int i = 0; i < numAssets; i++){
        std::string& hitVarName1 = (isKO ? "isKO" : "isKI") + Format::toString(i + 1);
         //use hitVarname1 with some other function        
         }
4

3 回答 3

1

You are creating a new string within your loop every time, so creating a reference to it means you are trying to create a reference to an r-value, which cannot be referenced since it has no address (until it is assigned).

Remove the & from the declaration type in your assignment and it should work, or change it to const std::string&, since compilers often allow temporaries to be assigned as references as long as they are constant.

于 2016-03-10T16:56:39.177 回答
1

这些字符串中的任何一个都不应该是参考。它们是对象,纯粹而简单。删除两个&s。

于 2016-03-10T17:34:04.320 回答
0

当你有类似的东西时,hitVarNameConst + Format::toString(i + 1)你会从中得到一个临时对象。C++ 中的临时对象称为右值(右值是一个历史术语,指的是通常右值位于赋值运算符的右侧(如 中a = get_b())。在左侧,您有一个右值。

非常量引用不能绑定到右值。您可以有一个 const 引用(这将对延长临时文件的生命周期产生很好的效果),或者您可以创建一个新实例std::string并将临时文件复制到那里。复制省略与移动语义将确保不会发生真正的复制。

于 2016-03-10T16:59:42.783 回答