san*_*pta 8 c++ language-lawyer move-semantics
我已经看到了相关的问题,他们主要谈论我们是否应该将const rvalue引用作为参数.但我仍然无法解释为什么在以下代码中调用非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());
}
Run Code Online (Sandbox Code Playgroud)
How*_*ant 13
以下是您的代码的略微修改版本:
#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());
}
Run Code Online (Sandbox Code Playgroud)
什么时候T == int,你得到非const过载.何时T是类类型,您将获得const重载.此行为属于8.2.2 [expr.type]/p2部分:
如果prvalue最初具有类型" cv
T",其中T是cv非限定的非类非数组类型,则表达式的类型T在任何进一步分析之前被调整.
翻译:该语言没有const合格的标量prvalues.他们根本就不存在.