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        
         }

Answers


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


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.


When you have something like hitVarNameConst + Format::toString(i + 1) you get a temporary object out of it. A temporary object in terms of C++ is called an rvalue (rvalue is a historic term, referring to the fact that usually rvalues are found on the right-hand side of the assignment operator (as in a = get_b()). On the left-hand side you have an rvalue.

Non-const references can not be bound to rvalues. You can either have a const reference (which will have a nice effect of extending the lifetime of the temporary) or you can create a new instance of std::string and copy your temporary there. Copy-elision together with move semantics will ensure no real copying will be taking place.


Need Your Help

Sort by varchar column

sql sql-server sorting sql-server-2014 varchar

In ms sql database table files_master I have a column named 'AstNum' varchar(100) it contain data like:

iphone setting UITextView delegate breaks auto completion

iphone autocomplete delegates uitextview uitextviewdelegate

I have a UITextField that I would like to enable auto completion on by: