[英]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 编译器:VS2003
Your function needs to take const std::string&
for you to use it like that. 你的函数需要使用const std::string&
就像你那样使用它。
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. C ++有一个规则,即rvalue(在你的情况下,是一个从字符串文字创建的临时std::string
)可以用const引用绑定,但不能绑定到非const引用。
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. 但是假设一个采用非const引用的函数这样做,因为它的主要目的是修改该参数。 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. 无论如何,并非所有的rvalues都是临时的:有些是真正无法修改的文字。
If you can't change the function AddNodeValue, then you can work around it: 如果您无法更改AddNodeValue函数,那么您可以解决它:
std::string valstr("modvalue");
document.AddNodeValue(modvalue, valstr);
// valstr might have changed, check the documentation of AddNodeValue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.