Tony The Lion
Tony The Lion

Reputation: 63200

passing a string literal to a function that takes a std::string&

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

Upvotes: 22

Views: 17174

Answers (1)

Steve Jessop
Steve Jessop

Reputation: 279265

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

Upvotes: 37

Related Questions