为什么左值可以传递给构造函数采用const ref rvalue?

Rol*_*lie 1 c++

例如:

#include <iostream>
#include <cstring>

using namespace std;

struct Square
{
    Square()
    {
        str = new char[10];
        strcpy(str, "Hello");
    }

    ~Square()
    {
        delete str;   
    }

    void print()
    {
        cout << "str = '" << str << "'" << endl;
    }

    char * str;    
};

class foo
{
public:
    typedef const Square & sqcref;
    typedef Square & sqref;
    foo(sqref && _ref)
    {
        fooStr = _ref.str;
        _ref.str = 0;
    }

    char * fooStr;
};

int main()
{
    Square s;
    s.print();
    foo f(s);
    s.print();
}
Run Code Online (Sandbox Code Playgroud)

输出:

str ='
Hello'str ='

在构造函数中foo,它期望一个rvalue到a Square &,但传入的是一个Square &左值.为什么这样做?

bar*_*top 8

它的工作原理是由于C++ 11中的参考折叠规则.简单地说,一个人无法创建对值的引用.因此,"引用参考"会遵循以下规则而崩溃

Val && && - > Val &&

Val &&& - > Val&

Val && - > Val&

Val &&& - > Val&

所以在你的情况下sqref &&(Square & &&崩溃)Square &.所以这是正常的左值参考.

  • 是的,这是有道理的.mpark在1分钟内击败了你的答案 - 谢谢所有相同的:) (2认同)