fakl
fakl

Reputation: 127

C++ Move constructor for object with std::vector and std::array members

I'm currently implementing a Vector class that is supposed to handle the math. This class has two members std::vector<double> vector_ and std::array<std::size_t, 2> size_.

Now I want to write a move constructor Vector(Vector&& other);. I've tried multiple ways, including Vector(Vector&& other) = default;, but none seems to do the job correctly. I always end up with both objects having the same size_ array, instead of the other having {0, 0}.

Aren't the default move constructor or std::move(...) supposed to move the contents and set the other's content to their default values?

Upvotes: 1

Views: 537

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

[...] and set the other's content to their default values?

No. When not stated otherwise a moved from object is in a valid, but unspecified state. Setting all elements to some default would be rather wasteful.

Further, a std::array does contain the elements. Its not just a pointer to some dynamically allocated elements that could cheaply be moved. The elements are right within the array. Hence you can only move the individual elements, the array as a whole can only be copied. A std::array is moveable when its elements are moveable, otherwise moving it will merely make a copy. For details I refer you to Is std::array movable?.

TL;DR

Vector(Vector&& other) = default; is fine. You just expected it do something it does not do. Neither does moving set the moved from elements to some default, nor does moving the std::array<size_t,2> actually move the elements, rather it copies them.

Upvotes: 1

Related Questions