gpt4 book ai didi

c++ - 为什么可以将左值传递给采用 const ref 右值的构造函数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:18:08 27 4
gpt4 key购买 nike

例如:

#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 & 的右值,但传入的是一个 Square & 左值。为什么会这样?

最佳答案

由于 reference collapsing 而有效C++11 中的规则。简而言之,不能创建对值引用的引用。因此,“对引用的引用”按照以下规则折叠

Val && && -> Val &&

Val & && -> Val &

Val & & -> Val &

Val && & -> Val &

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

关于c++ - 为什么可以将左值传递给采用 const ref 右值的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50578585/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com