0

Sometimes you still want the default move-constructor behavior (member-wise move), but also want to modify the moved-from object. Take the following scenario, for example

class Base{...}; // some move-constructible class
class Member{...}; // also move constructible

class Derived : public Base
{
public:
    // does member-wise move, but nothing more
    // Derived(Derived &&) = default;

    // does member-wise move, same as default
    // and also modifies `other`
    Derived(Derived && other)
        : a(std::move(other.a))
        , b(std::move(other.b))
        , ... // the rest of members
    {
        other.put_into_invalid_state_or_something();
    }

    //...............................................
    //      More functions
    //...............................................

private:
    // a lot of members...
    Member a,b,c,d,e,f,g,h,i;
};

This may be a silly question, but is there any way to avoid writing the move for each member?

DeltA
  • 564
  • 4
  • 12
  • 4
    "// a lot of members..." this can be a sign of a bad design. Maybe try and group various members into their own classes if it makes logical or semantic sense. – bolov Mar 04 '22 at 09:04
  • 2
    1. How do you decide which variable should be invalidate? 2. Why doesn't it invalidate itself? – Louis Go Mar 04 '22 at 09:05
  • You could make `Base` have a `make_invalid`-move constructor: https://godbolt.org/z/aEf449zdY – chtz Mar 04 '22 at 09:09
  • 2
    _Why_ do you want to do this? To prevent "use after move"? – JHBonarius Mar 04 '22 at 09:58
  • what exactly is `put_into_invalid_state_or_something()` ? After you moved the members the moved from object is already a moved from object. Also moved from objects should be in a valid state, not in an invalid state – 463035818_is_not_an_ai Mar 04 '22 at 10:06
  • 1
    Can't you group member which need/affect `put_into_invalid_state_or_something();` in a dedicated struct? Then only that struct would require special treatment., and your move constructor of `Derived` can then be defaulted. – Jarod42 Mar 04 '22 at 13:01

0 Answers0