Search code examples
c++c++11move

move assignment to object with const value


I have a struct like this:

struct OBJ {
  int x;
  const int y;
  OBJ& operator=(OBJ &&oth)
  {
    y = oth.y; // this is disallowed
    return *this;
  }
}

And an example code

void func() {
  static OBJ obj;
  OBJ other; // random values
  if(conditon)
    obj = std::move(other); //move
}

I understand this as obj is Non const OBJ with const member y. I can't change just y but I should be able to change whole object (call destructor and constructor). Is this possible or the only proper solution is to remove my const before y, and remember to don't change by accident?

I need to store my static obj between func call but if condition is true i want to move other object in place of this static object.


Solution

  • I would suggest moving to std::unique_ptr:

    void func() {
      static std::unique_ptr<OBJ> obj = std::make_unique<OBJ>();
      std::unique_ptr<OBJ> other = std::make_unique<OBJ>(); // random values
      if(condition)
        obj = std::move(other); //move
    }
    

    This should be your choice in many cases where there is a need to move something that cannot be moved, to hold an unknown polymorphic type or any other case where you cannot deal with the actual type.