【发布时间】:2020-07-20 10:30:08
【问题描述】:
#include <iostream>
using namespace std;
class foo {
public:
foo() {}
foo(const foo& other) {cout << "foo's copy constructor " << endl;}
foo(foo&& other) {cout << "foo's move constructor " << endl;}
foo(const foo&& other) {cout << "foo's move constructor with const ref ref" << endl;}
};
class bar {
public:
bar(const foo& f) : f_(move(f)) {}
foo f_;
};
int main()
{
foo f;
bar b(f);
}
在上面的代码中,在没有移动构造函数--foo(const foo&& other)的情况下,右值引用move(f)被隐式转换为const引用,因此调用了 foo 的复制构造函数。
我的问题是为什么 const 右值引用隐式转换为 const 引用而不是编译器错误?具体来说,如果我注释掉最后一个移动构造函数,则调用 foo 的复制构造函数。
【问题讨论】:
-
澄清一下,你是在问为什么问题中的代码没有给出错误?如果您实际上是要询问没有显示其中一个构造函数的代码,请对代码进行编辑。
-
右值引用仍然是引用,因此它可以绑定到 const 左值引用。但是 const 右值引用没有意义,因为 const 对象不能被移出。
-
@RemyLebeau stackoverflow.com/questions/4938875/…
-
@M.M 我的问题是关于从 const ref ref 到 const ref 的隐式转换以及为什么允许它(转换)而不是编译器错误。在我的代码中,如果最后一个移动构造函数被注释掉,则调用 foo 的复制构造函数。由于从 const ref ref 到 const ref 的隐式转换,调用了复制构造函数。我期待一个警告或错误,但不知道这种隐式转换。所以我想知道是否有任何理由允许在 C++ 中进行这种隐式转换。
-
@bigdata2 这里没有隐式转换,引用参数直接绑定到实参
标签: c++