Reputation: 121
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
}
Upvotes: 0
Views: 1531
Reputation: 76245
Neither one of those strings should be a reference. They're objects, pure and simple. Remove the two &
s.
Upvotes: 1
Reputation: 62553
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.
Upvotes: 0
Reputation: 2181
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.
Upvotes: 1