2

I'm implementing a move constructor and need to initialize other back to it's original state, as implemented in the default constructor. Is this possible or do I need to duplicate the code?

class Class
{
  Class() { /* code to duplicate */ }
  Class(Class&& other) :
    mMember(other.mMember) {
    other.Class(); // code to duplicate?
  }
};

I know other.Class() is invalid here and I know that constructors can call each other with C++11 now.

dromodel
  • 9,581
  • 12
  • 47
  • 65

1 Answers1

4

The best way would be to reassign it. Since the object is already constructed, it would be a mistake to call the constructor again.

However, you can create an instance and call the assignement operator:

Class(Class&& other) noexcept : mMember(std::move(other.mMember)) {
    other = Class{};
}

Another way would be to default construct your class and swap values with the old one:

Class(Class&& other) noexcept {
    std::swap(mMember, other.mMember);
}

If you really need other to take the value it would from calling the default constructor, you can do this:

Class(Class&& other) noexcept : Class() {
    std::swap(mMember, other.mMember);
}

It will call the default constructor in the new object and then swap the values from the other object.

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
  • 1
    The move constructor should [delegate](https://stackoverflow.com/questions/308276/can-i-call-a-constructor-from-another-constructor-do-constructor-chaining-in-c) to the default constructor. – jxh Sep 03 '19 at 18:44
  • 1
    The ask was to restore `other` to the state of a default constructed object... (the delegation comment only applies to your `swap` suggestion). – jxh Sep 03 '19 at 18:46
  • @jxh, true, but I assume OP want's to do that so it's moved properly. The default constructed values may suffice. I will add a section in the answer. – Guillaume Racicot Sep 03 '19 at 18:51