c++pointerscompiler-errorsconst-pointer

invalid initialization of non-const reference of type std::string& - how to remove


I am getting an error:
error: invalid initialization of non-const reference of type 'std::string& {aka std::basic_string&}' from an rvalue of type 'std::basic_string'

The code is:

 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
      }

How do I remove this error? Earlier I was trying the following code, it was still throwing the same error:

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

Solution

  • Neither one of those strings should be a reference. They're objects, pure and simple. Remove the two &s.