4

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?

Evg
  • 25,259
  • 5
  • 41
  • 83
Alakanu
  • 325
  • 2
  • 11

1 Answers1

7

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.

MRB
  • 3,752
  • 4
  • 30
  • 44
  • Note that the correct answer depends on the allocator. For `std::allocator` (as the OP specified) this is a correct answer. For more details see: https://stackoverflow.com/a/17735913/576911 – Howard Hinnant Dec 18 '19 at 14:15
  • @HowardHinnant Thank you for reminding that subtle point. I have edited my answer, could you please check if there is any mistake in answer. – MRB Dec 18 '19 at 18:01
  • Looks perfect! :-) – Howard Hinnant Dec 18 '19 at 18:19