[英]Does it make sense to implement the copy-assignment operator in a class with all const data members?
[英]std::move and rvalue assignment operator for a class with const data members
里面有class A
,里面有const
成员。 要编写其右值赋值运算符,我必须显式声明它。 例如
struct A {
const int i;
// other members and constructors
// A& operator= (A&&) = default; // This doesn't work due to `i`
A& operator= (A&&); // <--- what should be the body?
};
问题:1 ---上述赋值运算符的正确语法是什么
问题:2 ---如果我们将其与模板一起使用,这是否合法?
template<class T>
struct move {
T& operator= (T&& t); // <--- same code here with `static_cast<T&>(*this)`
};
struct A : move<A> {
const int i;
// ...
using move<A>::operator=;
};
上述赋值运算符的正确语法是什么?
如果i
是const
不能分配
的
,所以
赋值运算符的实现应该简单地返回
赋值运算符应保持含蓄*this
delete
“编辑。 默认的,由编译器生成的赋值运算符对每个非静态数据成员执行按成员的赋值。 对于无法分配的对象,无法完成此操作。
,因此最好的做法是仅使用return语句明确定义它
。 不允许将类从语义上移开是没有意义的:
如果我们将其与模板一起使用,那是合法的方法吗?
是的,那是合法的。
但是与在您的班级中定义它相反,我看不出这样做的理由。
您仍然需要一个构造函数来显式初始化i
。 除此之外,它确实允许移动分配,同时忽略i
的const
-ness,否则将不允许这样做。
主体将是:
A& A::operator= (A&& a)
{
// code to move-assign other members
return *this;
}
由于i
为常量,因此无法在此函数中更新i
。
我看不到您在示例2中要做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.