为什么在这种情况下调用非 const 右值移动构造函数?
Why is a non-const rvalue move constructor called in this case?
我看过相关的问题,他们主要讨论我们是否应该将 const 右值引用作为参数。但我仍然无法理解为什么在以下代码中调用了 非常量移动构造函数:
#include <iostream>
using namespace std;
class A
{
public:
A (int const &&i) { cout << "const rvalue constructor"; }
A (int &&i) { cout << "non const rvalue constructor"; }
};
int const foo (void)
{
const int i = 3;
return i;
}
int main (void)
{
A a(foo());
}
这里是你的代码的一个稍微修改的版本:
#include <iostream>
#if 0
using T = int;
#else
struct T {T(int){}};
#endif
using namespace std;
class A {
public:
A (T const &&i) { cout << "const rvalue constructor"; }
A (T &&i) { cout << "non const rvalue constructor"; }
};
T const
foo (void)
{
const T i = 3;
return i;
}
int main()
{
A a(foo());
}
当 T == int
时,您得到非常量重载。当 T
是 class 类型时,您会得到 const 重载。此行为不属于第 8.2.2 节 [expr.type]/p2:
If a prvalue initially has the type “cv T
”, where T
is a cv-unqualified non-class, non-array type, the type of the expression is adjusted to T
prior to any further analysis.
翻译:该语言没有 const
限定的标量纯右值。它们根本不存在。
我看过相关的问题,他们主要讨论我们是否应该将 const 右值引用作为参数。但我仍然无法理解为什么在以下代码中调用了 非常量移动构造函数:
#include <iostream>
using namespace std;
class A
{
public:
A (int const &&i) { cout << "const rvalue constructor"; }
A (int &&i) { cout << "non const rvalue constructor"; }
};
int const foo (void)
{
const int i = 3;
return i;
}
int main (void)
{
A a(foo());
}
这里是你的代码的一个稍微修改的版本:
#include <iostream>
#if 0
using T = int;
#else
struct T {T(int){}};
#endif
using namespace std;
class A {
public:
A (T const &&i) { cout << "const rvalue constructor"; }
A (T &&i) { cout << "non const rvalue constructor"; }
};
T const
foo (void)
{
const T i = 3;
return i;
}
int main()
{
A a(foo());
}
当 T == int
时,您得到非常量重载。当 T
是 class 类型时,您会得到 const 重载。此行为不属于第 8.2.2 节 [expr.type]/p2:
If a prvalue initially has the type “cv
T
”, whereT
is a cv-unqualified non-class, non-array type, the type of the expression is adjusted toT
prior to any further analysis.
翻译:该语言没有 const
限定的标量纯右值。它们根本不存在。