[英]Bind rvalue reference to (auto generated) lvalue
My search found many posts on rvalue binding to lvalue but not anything similar. 我的搜索发现许多关于将右值绑定到左值的帖子,但没有类似的内容。 Sorry if it is a duplicate. 抱歉,如果它是重复的。
struct StrHolder {
StrHolder(std::string&& s) : name(s) {}
void Print() const { std::cout << "My name is " << name << std::endl; }
std::string name;
};
int main()
{
StrHolder s{"Tom"}; // (1) - OK, as expected
s.Print();
std::string n1 {"Angi"};
StrHolder p{std::move(n1)}; // (2) - OK, also as expected
p.Print();
//StrHolder q{n1}; // (3) - NOT OK. Also expected. Cannot bind rvalue reference to lvalue
//q.Print();
auto name1 {"Bon"}; // name1 is an lvalue
StrHolder z{name1}; // (4) - Why is this OK ?
z.Print();
return 0;
}
The variable 'name1' declared as auto, above is an lvalue. 上面声明为auto的变量“ name1”是一个左值。 Therefore, initialization of 'z' should fail but it does not. 因此,“ z”的初始化应该失败,但不会失败。
Am I missing anything here ? 我在这里想念什么吗?
name1
is an lvalue... but it's not a std::string
, it's a char const*
. name1
是一个左值...但它不是std::string
,而是一个char const*
。 Constructing a StrHolder
from it involves making a temporary std::string
using its implicit constructor from char const*
, then invoking StrHolder::StrHolder()
with an rvalue reference to that temporary. StrHolder
构造一个StrHolder
涉及使用从char const*
隐式构造一个临时std::string
,然后调用带有该临时值的右值引用的StrHolder::StrHolder()
。 name1
gets left alone, and is never moved from. name1
被留下,并且永远不会移开。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.