[英]What is the difference between “std::string const &s” and “const std::string &s”?
[英]What is the difference between const string &s and string &s?
这是c++ 底漆的代码:
string::size_type findChar(const string &s, char c, string::size_type & occurs){
auto ret = s.size();
occurs = 0;
for (decltype(ret) i = 0; i != s.size(); ++i){
if (s[i] == c){
if (ret == s.size())
ret = i;
occurs++;
}
}
return ret;
}
int main () {
string::size_type ctr;
cout << findChar("hello, world!", 'o', ctr);
}
从const string &s
中删除const
后发生错误。
错误:无法将 'std::__cxx11::string&' {aka 'std::__cxx11::basic_string&'} 类型的非常量左值引用绑定到 'std::__cxx11::string' {aka 'std' 类型的右值::__cxx11::basic_string'} cout << findChar("hello, world,", 'o'; ctr);
我想知道,在这种情况下, const
关键字会改变编译器的哪些行为? 谢谢你帮助我。
像"hello, world!"
这样的字符串文字不是std::string
。 因此,要调用您的 function,编译器必须为您创建一个std::string
。 这样的 object 称为临时。 所以在第一种情况下,编译器使用"hello, world!"
创建一个std::string
然后将该临时字符串绑定到引用参数s
。
但是 C++ 有一条规则,您不能将临时对象绑定到非常量引用。 但是,当您将s
从const std::string&
更改为std::string&
时,您是在要求编译器完全这样做。 这就是错误消息告诉您的内容。
如果您将代码更改为此
string::size_type ctr;
string hello = "hello, world!";
cout << findChar(hello, 'o', ctr);
即使没有 const,它现在也可以编译。 这里的区别在于编译器不再创建临时std::string
(因为hello
已经是std::string
)。 所以关于临时和非常量引用的规则不适用。
std::string 是 class。 const char* 是一个指向 memory 的指针,它希望包含一个以 null 结尾的字符串。 您可以使用 std::string 按值传递并进行复制,而无需调用 strcpy 之类的函数。
尽可能使用 std::string ,在需要指向字符串的指针时使用 c_str() 方法,例如,对于较旧的 C 库。
在调用代码中,为s
传递的 object 是"hello, world!"
,这是一个字符串,其内容不能更改。 在 function findChar
中,类型const string &s
是名为s
的对类型为const string
的 object 的引用。 这两种类型匹配,因此编译成功完成。
但是,参数string &s
表示一个名为s
的引用,指向string
类型的 object - 这是一个可变(可变)字符串。 但是传入的参数( "hello, world!"
)是一个无法更改的字符串。 发生这种情况时,编译器会指示类型不匹配错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.