lundi 3 août 2015

C++ Move assignment operator: Do I want to be using std::swap with POD types?

Since C++11, when using the move assignment operator, should I std::swap all my data, including POD types? I guess it doesn't make a difference for the example below, but I'd like to know what the generally accepted best practice is.

Example code:

class a
{

     double* m_d;
     unsigned int n;

public:

     /// Another question: Should this be a const reference return?
     const a& operator=(a&& other)
     {
         std::swap(m_d, other.m_d); /// correct
         std::swap(n, other.n); /// correct ?
         /// or
         // n = other.n;
         // other.n = 0;
     }
}

You might like to consider a constructor of the form: - ie: there are always "meaningful" or defined values stores in n or m_d.

a() : m_d(nullptr), n(0)
{
}

Aucun commentaire:

Enregistrer un commentaire