C++ std::具有常量数据成员的类的move和rvalue赋值运算符

C++ std::具有常量数据成员的类的move和rvalue赋值运算符,c++,c++11,move-semantics,assignment-operator,rvalue-reference,C++,C++11,Move Semantics,Assignment Operator,Rvalue Reference,有class A和const成员。要编写它的右值赋值运算符,我必须显式声明它。e、 g 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

class A
const
成员。要编写它的右值赋值运算符,我必须显式声明它。e、 g

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?
};
结构A{ 常数int i; //其他成员和建设者 //A&operator=(A&&)=default;//由于'i'的原因,此操作不起作用` A&operator=(A&&);//主体将是:

A& A::operator= (A&& a)
{
    // code to move-assign other members

    return *this;
}
无法在此函数中更新
i
,因为
i
是常量

在示例2中,我看不出您想要做什么

上述赋值运算符的正确语法是什么

如果
i
const
,则无法对其赋值,因此赋值运算符的实现应简单地返回
*此
赋值运算符应保留为隐式
delete
'ed。默认情况下,编译器生成的赋值运算符对每个非静态数据成员执行成员赋值。这无法为无法分配的对象执行此操作。因此,最好的做法是仅使用一个return语句显式定义它。不允许从中移动类在语义上没有意义:

如果我们将其与模板一起使用,这是合法的方式吗

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
。除此之外,它允许移动赋值,同时忽略
i
const
,否则这将无法实现。

有效的方法是什么?第(1)和(2)两种方法没有操作。@IgorTandetnik,我在右值赋值方面有点新手。语法错误吗?
std::move()
只是右值的转换。因为
a()
是一个右值,不需要强制转换。你甚至给一个类分配一个
const
成员是什么意思?它对所有实例都保证相等吗?本质上
const
禁用赋值(复制和移动),因此函数将是空的。这些方法只会使对象看起来好像可以移动,但实际上无法移动。最好的做法是用一个返回语句来显式定义它-我不同意,对于这样一个类,最好的做法是让它不可赋值,而不是试图假装它是。@Praetorian是的,我只是t散步时,我突然想到我说的话是愚蠢的!哈哈