Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move constructor C++11

I am looking at some code that I have inherited and it has a matrix class which implements 2D matrices in C++ and has move constructors and assignment operator.

The way it is implemented is as follows:

template<typename T, int rows, int cols>
class matrix_data {
    ...
    std::unique_ptr<T[]> data_;
    // Some definitions
    typedef matrix_data<T, rows, cols> this_type

    matrix_data(this_type && other)
    {
        std::swap(data_, other.data_);
    }
};

Now, I am not sure why the data pointers are being swapped here. I thought it should be something like

data_ = std::move(other.data_);

I am guessing with the swap it is still ok because the other instance should be in an invalid state anyway after the move.

My question is whether I can replace the statement with data_ = std::move(other.data_); Is there some unique_ptr deletion stuff that is the reason for doing the swap instead of the move i.e. if I do the move would the original data be deleted correctly?

like image 754
Luca Avatar asked Oct 30 '22 03:10

Luca


1 Answers

To answer your question:

Yes, you could replace the swapping with

data_ = std::move(other.data_);

but as the comments suggest, that's happening anyway when you do not implement the move constructor, as long as you do not implement neither a copy constructor, copy assignment operator, move assignment operator or destructor. If you have implemented one of the above, marking the move constructor as =default will also do the job.

Swapping the objects' contents is indeed not necessary in this case as there is actually nothing to swap, because this being a (move) constructor, this->data_ does not point to any previously allocated memory location that should be freed after the pointer to it has been overwritten.

Therefore swapping is usually done when implementing the move assignment operator, because in this case this->data_ usually holds a pointer to a memory location that needs to be freed sometime. By putting this pointer into the moved-from object, the memory it is pointing to will be freed when the destructor for the moved-from object is called.

like image 167
Angle.Bracket Avatar answered Nov 12 '22 16:11

Angle.Bracket