I was watching a Bjarne Stroustrup talk and the section was on move operators and their benefits.
He mentions here that an explicit move constructor such as:
Matrix(Matrix&& a)
{
rep = a.rep;
a.rep = {};
}
Is "c-style" and "cryptic".
He then goes on to say that in a lot of cases, writing copy/move operators can be avoided; he provides the following example here:
class Matrix
{
vector<double> elem;
// ... matrix access...
}
He states that this Matrix class "inherits" resource management from vector and that the copy/move constructors are implicitly generated it.
Could someone help clarify what he means by this? How would I take a Matrix object and utilize move semantics if I didn't define a move operator for Matrix?
Move constructors are implicitly defined when
- X does not have a user-declared copy constructor,
- X does not have a user-declared copy assignment operator,
- X does not have a user-declared move assignment operator,
- X does not have a user-declared destructor, and
- the move constructor would not be implicitly defined as deleted.
So in the case of Matrix
the move constructor is implicitly defined. And the implicit move constructor does its best to move its data members. And std::vector
is movable, so it moves the instance of the vector in the Matrix
struct.