0

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        
         }
Mayank Raj
  • 121
  • 2
  • 12

3 Answers3

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.

Matt Jordan
  • 2,133
  • 9
  • 10
  • Not often but always. You can always extend the life of a temporary by using a `const &` – NathanOliver Mar 10 '16 at 16:58
  • @NathanOliver Some people are stuck with older versions of C++ compilers, but correct r-value handling is relatively recent compared to some of the compilers still in use (C++11, for the bulk of it). – Matt Jordan Mar 10 '16 at 17:01
  • @MattJordan, you were able to bind const references to rvalues since the creation of references. – SergeyA Mar 10 '16 at 17:02
  • @MattJordan No. Since the beginning off C++ you could bind a temporary to a `const &` – NathanOliver Mar 10 '16 at 17:02
1

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

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
0

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.

SergeyA
  • 61,605
  • 5
  • 78
  • 137