Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do derived classes need to implement move semantics when a base provides it?

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)
{
}
like image 355
jww Avatar asked Jul 31 '15 21:07

jww


Video Answer


1 Answers

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.

like image 147
Cory Kramer Avatar answered Sep 21 '22 03:09

Cory Kramer