繁体   English   中英

为什么要将左值传递给采用const ref rvalue的构造函数?

[英]Why can an lvalue be passed into a constructor taking a const ref rvalue?

例如:

#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();
}

输出:

str ='Hello'
str ='

foo的构造函数中,它期望对Square &的值是rvalue,但是传入的是Square & lvalue。 为什么这样做?

由于C ++ 11中的引用折叠规则,因此它可以工作。 简而言之,不能创建对价值的参考。 因此,“引用引用”按照以下规则折叠

Val && &&-> Val &&

Val&&&-> Val&

Val&&-> Val&

Val &&&-> Val&

因此,在您的情况下, sqref && (即Square & && sqref && )折叠为Square & 因此,这是正常的左值参考。

这是由于参考崩溃 sqref&&其中sqrefT&折叠为T&

https://wandbox.org/permlink/eWeYLdI3l0vSpNvo

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM