简体   繁体   中英

std::move and rvalue assignment operator for a class with const data members

There is class A with const member inside it. To write its rvalue assignment operator, I have to declare it explicitly. eg

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?
};

Question: 1 --- What is the correct syntax for the above assignment operator

Question: 2 --- If we use it with templates, is that a legal way?

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=;
};

What is the correct syntax for the above assignment operator?

If i is const it can't be assigned, so the implementation of the assignment operator should simply return *this assignment operator should be left as implicitly delete 'ed. The default, compiler-generated assignment operator performs a member-wise assignment of each non-static data member. This can't be done for an object that can't be assigned. ,so your best course of action is to explicitly define it with just a return statement . Don't allow your class to be moved from it doesn't make sense semantically:

If we use it with templates, is that a legal way?

Yes that's legal. But I don't see a reason for doing that as opposed to defining it in your class.

You still need a constructor to explicitly initialize i . Other than that it does allow move assignment while ignoring the const -ness of i that would otherwise not allow this to be possible.

The body would be:

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

    return *this;
}

It is not possible to update i in this function because i is const.

I don't see what you are trying to do in example 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM