[英]What happens when a string literal passed as const string& to a function?
Here is an example from the C++ Primer : A function count()
declared as: 以下是C ++ Primer中的一个示例:函数
count()
声明为:
int count(const string & a, char b);
and called: 并呼吁:
count("abcde", 'a')
It works. 有用。 Here
"abcde"
is a string literal and passed to count()
as const string &
. 这里
"abcde"
是一个字符串文字,并作为const string &
传递给count()
。
But at the same time this code 但同时这段代码
string & s="abcde";
was wrong simply because we cannot assign a string
literal to a string &
. 之所以错,只是因为我们无法将
string
文字分配给string &
。
So what happened when "abcde"
was passed to count()
? 那么当
"abcde"
传递给count()
什么? Is there something like a temporary string be initialized by "abcde"
and then passed to count()
? 是否有类似临时字符串的东西由
"abcde"
初始化然后传递给count()
?
Is there something like a temporary string be initialized by
"abcde"
and then passed tocount()
?是否有类似临时字符串的东西由
"abcde"
初始化然后传递给count()
?
Yes, that's exactly what happens there. 是的,那就是那里发生的事情。
A temporary instance of std::string
is constructed using the implicit constructor (5) 使用隐式构造函数(5)构造
std::string
临时实例
basic_string( const CharT* s,
const Allocator& alloc = Allocator() );
and passed as rvalue reference to the function. 并作为rvalue引用传递给函数。
As for your second sample this would work with a const
reference as well: 至于你的第二个例子,这也适用于
const
引用:
const std::string& s = "abcde";
The point is a lvalue reference can't be initialized from a rvalue. 该点是左值参考不能从右值初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.