Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 281
Tony The Lion Avatar asked Oct 28 '10 15:10

Tony The Lion


1 Answers

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
like image 82
Steve Jessop Avatar answered Oct 02 '22 01:10

Steve Jessop