7

I finished reading Thomas Becker's "C++ Rvalue References". I have a couple questions on Rvalues and Rvalue references.

Suppose I have a simple array class:

template <class T>
MyArray
{
    ...
    T* m_ptr;  // Pointer to elements
    size_t m_count; // Count of elements
};

Further suppose it provides:

#if(__cplusplus >= 201103L)
MyArray(MyArray&& t)
  : m_ptr(std::move(t.m_ptr)), m_count(std::move(t.m_count))
{
    t.m_ptr = NULL;
    t.m_count = 0;
}
MyArray operator=(MyArray&& t)
{
    std::swap(*this, t);
    return *this;
}
#endif

Now, suppose I have a derived class that does not add new data members:

MyImprovedArray : public MyArray
{
    ...
};

What is required of MyImprovedArray?

Does it need a MyImprovedArray(MyImprovedArray&&) and MyImprovedArray& operator=(MyImprovedArray&&) also? If so, does it only need to perform the base class std::move? Or does it need to perform the std::swap too?

MyImprovedArray(MyImprovedArray&& t)
    : MyArray(t)
{
}
jww
  • 97,681
  • 90
  • 411
  • 885
  • In doubt, you may still do `MyImprovedArray(MyImprovedArray&&) = default;` – Jarod42 Aug 01 '15 at 00:34
  • As long as you don't have a virtual base, the defaults are fine. If you have a virtual base, [you may need to take a look at your copy/move assignment operators](http://stackoverflow.com/questions/17252869/danger-with-virtual-base-move-assignment-operators-when-they-are-now-allowed-to). – T.C. Aug 01 '15 at 02:51

1 Answers1

6

Rule of five (or zero) applies to the derived class, regardless of what the base class defines.

If your derived MyImprovedArray's move constructor isn't going to do anything special, don't define it, and let the compiler generate one.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • So I'm clear, that means I don't need to write anything in `MyImprovedArray`? That is, the declaration and `: MyArray(std::move(t))` (and empty body) are spurious? (Sorry to ask. In C++ I've been bitten a few times with the *"don't pay for it when you don't need it"* mantra. It ended poorly with virtual destructors). – jww Jul 31 '15 at 21:52
  • 4
    Correct (aside from a constructor obviously). If you do not define a destructor, move constructor, copy constructor, move assignment operator, or copy assignment operator then the compiler will make them for you (assuming the class is copyable/movable based on its members) – Cory Kramer Jul 31 '15 at 21:55