[ACCEPTED]-passing a string literal to a function that takes a std::string&-function

Accepted answer
Score: 32

Your function needs to take const std::string& for you to 19 use it like that.

C++ has a rule that an 18 rvalue (in your case, a temporary std::string which 17 is created from the string literal) can 16 be bound with a const reference, but not 15 a non-const reference.

As far as I know, this 14 restriction isn't due to any fundamental 13 implementation problem, since temporary 12 values can be modified in other ways. But a 11 function which takes a non-const reference 10 is assumed to do so because its main purpose 9 is to modify that argument. It doesn't usually 8 make a lot of sense to do that with a temporary, so 7 possibly banning it catches errors far more 6 than it prevents people doing something 5 worthwhile. Anyway, not all rvalues are 4 temporaries: some are literals which really 3 cannot be modified.

If you can't change the 2 function AddNodeValue, then you can work 1 around it:

std::string valstr("modvalue");
document.AddNodeValue(modvalue, valstr);
// valstr might have changed, check the documentation of AddNodeValue

More Related questions