Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to the left hand side std::vector resources on move assignment?

I was trying to find out if it's granted by the C++ 11 standard that the resources of a std::vector receiving a move assignment are freed.

I'll give you an example:

std::vector<int> a {1, 2};
std::vector<int> b {3, 4};
a = std::move(b);

Now what I'd be expecting is that both a and b are wrapping a regular array (usually) and they have a pointer to it, namely a_ptr and b_ptr. Now I think the move assignment among other things does a_ptr = b_ptr. Does the standard guarantee that the memory in a_ptr is freed before or by this?

like image 478
Alakanu Avatar asked Oct 28 '25 05:10

Alakanu


1 Answers

By taking a look at Table 71: Container requirements it is stated that container's internal structure will be destroyed.

a = rv => All existing elements of a are either move assigned to or destroyed

As Howard Hinnant has mentioned in the comments, there is a special case which has also been stated in above sentence:

All existing elements of a are either move assigned to or destroyed.

This spacial case is related to move-assignment operator and simply has 3 different states:

  1. propagate_on_container_move_assignment is true in lhs:

    In this case allocated memory in lhs is freed and the move operation is done. The allocator is also move assigned.

  2. propagate_on_container_move_assignment is false in lhs and the allocators from both sides are equal:

    In this case same sequence of operations is done except that there is no need to assign to the lhs allocator.

  3. propagate_on_container_move_assignment is false in lhs and the allocators from both sides are not equal:

    In this case because two allocators are not equal the allocator of lhs container cannot be used to manage the memory of the rhs container so the only option is to move assign rhs container items to the lhs container.

The last case explains why items in lhs container can be move assigned to. In any case the memory will be freed, reused or reallocated.

like image 60
MRB Avatar answered Oct 29 '25 20:10

MRB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!