将右值引用绑定到(自动生成的)左值

时间:2019-03-07 10:32:35

标签: c++ auto rvalue lvalue

我的搜索发现许多关于将右值绑定到左值的帖子,但没有类似的内容。抱歉,如果重复的话。

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;
}

上面声明为auto的变量“ name1”是一个左值。因此,“ z”的初始化应该失败,但不会失败。

我在这里错过了什么吗?

1 个答案:

答案 0 :(得分:4)

name1是一个左值...但它不是std::string,而是char const*。从中构造一个StrHolder涉及到使用std::string中的隐式构造函数制作一个临时char const*,然后使用对该临时对象的右值引用调用StrHolder::StrHolder()name1一个人呆着,永远不会离开。