c++ - Move constructor C++11 -


i looking @ code have inherited , has matrix class implements 2d matrices in c++ , has move constructors , assignment operator.

the way implemented follows:

template<typename t, int rows, int cols> class matrix_data {     ...     std::unique_ptr<t[]> data_;     // definitions     typedef matrix_data<t, rows, cols> this_type      matrix_data(this_type && other)     {         std::swap(data_, other.data_);     } }; 

now, not sure why data pointers being swapped here. thought should

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

i guessing swap still ok because other instance should in invalid state anyway after move.

my question whether can replace statement data_ = std::move(other.data_); there unique_ptr deletion stuff reason doing swap instead of move i.e. if move original data deleted correctly?

to answer question:

yes, replace swapping with

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

but comments suggest, that's happening anyway when not implement move constructor, long not implement neither copy constructor, copy assignment operator, move assignment operator or destructor. if have implemented 1 of above, marking move constructor =default job.

swapping objects' contents indeed not necessary in case there nothing swap, because being (move) constructor, this->data_ not point allocated memory location should freed after pointer has been overwritten.

therefore swapping done when implementing move assignment operator, because in case this->data_ holds pointer memory location needs freed sometime. putting pointer moved-from object, memory pointing freed when destructor moved-from object called.


Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -