I have a class like
class MyMatrix {
public:
MyMatrix() = default;
MyMatrix(const MyMatrix&) = default;
~MyMatrix() = default;
// some custom methods..
private:
std::vector<float> data;
}
since I have all my data in a vector I thought that RAII should take care of the memory.
My question is: should I also include a MyMatrix(MyMatrix&&) = default; line? Would my code benefit from this at all or would I do something wrong if I did?
When you provide a user-declared copy constructor (or copy assignment operator), neither the move constructor nor the move assignment operator are declared.
MyMatrix(const MyMatrix&) = default; // <- though `defaulted`, it *is* user-declared...
If you want your class to benefit from move semantics, in that case, you'll need to declare them by yourself (you can still default them as well). Since you have only members which have well defined copy and move semantics (the vector), the default implementation will be alright.
MyMatrix(MyMatrix&&) = default;
Adding that declaration would lead to the automatic deletion of the copy assignment operator. If you want it you'ld have to declare it as well!
In the end, you could just remove the declaration of the copy constructor and it would perform how you wish it would. (You'ld also have both the move and copy assignment operators automatically defaulted for you).
Here is a slideshare by Howard Hinnant on that matter (with beautiful tables) showing you what the compiler generates -or does not- depending on what you declare.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With