显式复制构造函数编译错误
explicit copy constructor compile error
我在检查 C++ 中的运算符重载时遇到了一些我没想到的事情,对此我有一些疑问。
我的复制构造函数声明并实现为
explicit Vector(const Vector& v);
Vector::Vector(const Vector& v) :
_x(v._x), _y(v._y), _z(v._z) {}
然后我重载复合赋值运算符
Vector Vector::operator+(const Vector& v) const
{
Vector tmp(*this);
tmp += v;
return tmp;
}
Vector Vector::operator-(const Vector& v) const
{
Vector tmp(*this);
tmp -= v;
return tmp;
}
然而,在 return
语句中我得到一个错误 no matching constructor for initialization of 'Vector'
。
因为我唯一添加到构造函数的是 explicit
关键字,所以我删除了它并且代码编译得很好,为什么?
我也在检查 C++11 的新内容,发现我可以像移动构造函数一样声明我的构造函数
explicit Vector(const Vector&& v);
并且代码编译得很好。如果我这样做,我是否必须同时拥有复制和移动构造函数?
explicit Vector(const Vector& v);
explicit Vector(const Vector&& v);
或者仅仅使用移动构造函数就可以了?如果我想坚持使用 C++11,正确的方法是什么?
您定义了显式复制构造函数,但是函数
Vector Vector::operator+(const Vector& v) const
和
Vector Vector::operator-(const Vector& v) const
必须按值 return,并且不能再这样了,因为 explicit
(换句话说,它们不能将 tmp
复制到 returned 对象中)。
I also was checking new stuff from C++11 and occurred that I can declare my constructor like a moving-constructor
explicit Vector(const Vector&& v);
and the code compiles just fine. If I do that, do I have to have both copy and move constructors?
不确定我是否理解您的意思。如果您只声明一个显式移动构造函数(这将阻止编译器生成默认复制构造函数),您将遇到同样的问题。我无法生成 "compilable" 代码。
按值返回对象要求可以执行隐式复制构造。使复制构造函数显式防止这种情况。
无论编译器是否选择不调用复制构造函数(例如 return 值优化)都是如此。
我在检查 C++ 中的运算符重载时遇到了一些我没想到的事情,对此我有一些疑问。
我的复制构造函数声明并实现为
explicit Vector(const Vector& v);
Vector::Vector(const Vector& v) :
_x(v._x), _y(v._y), _z(v._z) {}
然后我重载复合赋值运算符
Vector Vector::operator+(const Vector& v) const
{
Vector tmp(*this);
tmp += v;
return tmp;
}
Vector Vector::operator-(const Vector& v) const
{
Vector tmp(*this);
tmp -= v;
return tmp;
}
然而,在 return
语句中我得到一个错误 no matching constructor for initialization of 'Vector'
。
因为我唯一添加到构造函数的是 explicit
关键字,所以我删除了它并且代码编译得很好,为什么?
我也在检查 C++11 的新内容,发现我可以像移动构造函数一样声明我的构造函数
explicit Vector(const Vector&& v);
并且代码编译得很好。如果我这样做,我是否必须同时拥有复制和移动构造函数?
explicit Vector(const Vector& v);
explicit Vector(const Vector&& v);
或者仅仅使用移动构造函数就可以了?如果我想坚持使用 C++11,正确的方法是什么?
您定义了显式复制构造函数,但是函数
Vector Vector::operator+(const Vector& v) const
和
Vector Vector::operator-(const Vector& v) const
必须按值 return,并且不能再这样了,因为 explicit
(换句话说,它们不能将 tmp
复制到 returned 对象中)。
I also was checking new stuff from C++11 and occurred that I can declare my constructor like a moving-constructor
explicit Vector(const Vector&& v);
and the code compiles just fine. If I do that, do I have to have both copy and move constructors?
不确定我是否理解您的意思。如果您只声明一个显式移动构造函数(这将阻止编译器生成默认复制构造函数),您将遇到同样的问题。我无法生成 "compilable" 代码。
按值返回对象要求可以执行隐式复制构造。使复制构造函数显式防止这种情况。
无论编译器是否选择不调用复制构造函数(例如 return 值优化)都是如此。