I have the following function
void AddNodeValue(XMLNode& node, std::string& value);
I want to use it like this:
document.AddNodeValue(modvalue,"modvalue");
and the compiler complains:
error C2664: 'void XML::XMLDocument::AddNodeValue(XML::XMLNode &,std::string &)' : cannot convert parameter 2 from 'const char [9]' to 'std::string &'
A reference that is not to 'const' cannot be bound to a non-lvalue
I don't get why that is wrong?
Compiler: VS2003
Your function needs to take const std::string&
for you to use it like that.
C++ has a rule that an rvalue (in your case, a temporary std::string
which is created from the string literal) can be bound with a const reference, but not a non-const reference.
As far as I know, this restriction isn't due to any fundamental implementation problem, since temporary values can be modified in other ways. But a function which takes a non-const reference is assumed to do so because its main purpose is to modify that argument. It doesn't usually make a lot of sense to do that with a temporary, so possibly banning it catches errors far more than it prevents people doing something worthwhile. Anyway, not all rvalues are temporaries: some are literals which really cannot be modified.
If you can't change the function AddNodeValue, then you can work around it:
std::string valstr("modvalue");
document.AddNodeValue(modvalue, valstr);
// valstr might have changed, check the documentation of AddNodeValue
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With