Can pop_back () ever reduce the capacity of a vector? (C ++)

According to the C ++ standard, is std::vector<T>::pop_back()it ever allowed to reduce the capacity of a vector?

I ask because I would like to get a guarantee that the following code will not throw an exception from memory:

my_vec.pop_back();
if (...)
    my_vec.push_back(...);

Suppose that my_vecis std::vector<int>.

I assume there are three possibilities:

  • Yes, this can happen in both C ++ 03 and C ++ 11.

  • No, C ++ 11 prohibits this (but C ++ 03 does not).

  • No, both C ++ 03 and C ++ 11 forbid this.

Yes, my question is related to Does std :: vector.pop_back () change the capacity of a vector? but my question is specifically about what the standard guarantees.

, std::vector.pop_back() ? , , , pop_back().

+4
3

http://en.cppreference.com/w/cpp/container/vector/pop_back

, back() end(), .

. C++11, , 03. .

: : C++03: [lib.container.requirements] (23.1), 10:

no erase(), pop_back() pop_front() .

23.2.1/10 N3337 (~ C++11).

+7

. - -, . C++11 , .

, ref :

,
     .

, .

:

,
     .
    , ,
    , ,      , .

C++11 std::vector<>::shrink_to_fit() ( . 1- ). (tnx Psyduck). , , , , .

, capacity, ref

, , .

, > , .

, > .

, capacity pop_back, ref - , - .

, , ref capacity, , , , capacity .

:

#include <iostream>
#include <vector>

int main() {
  const int N = 1000000;

  std::vector<int> v1;
  v1.reserve(N);
  for (int i = 0; i < N; ++i) {
    v1.push_back(i);
  }

  std::cout << v1.capacity() << " and size = " << v1.size() << std::endl;

  for (int i = 0; i < N - 2; ++i) {
    v1.pop_back();
  }

  std::cout << v1.capacity() << " and size = " << v1.size() << std::endl;

  return 0;
}

:

1000000 and size = 1000000
1000000 and size = 2

capacity .

[EDIT]

question, , . :

1)

STL 17. ( , OP ) std::vector. "" , > , .

2)

, .

3)

, GCC - , , ( ), Allocator , Allocator reallocate(). , , .

.

[EDIT.2]

question :

Q: pop_back() capacity?

A: .

( , ), , pop_back() - .

+4

. , std::vector -, std:: allocator, std:: allocator , , , .

, , stackoverflow ++ ?

" std::vector (, , ). . - KeithB Jun 23 '10 at 21: 39" ( )

realloc std:: allocator, :

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1953.html

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2045.html

The articles do not explicitly state that std :: allocator is forbidden to extend std :: allocator, but - they only claim that this is not necessary. They also do not explicitly state that std :: vector is forbidden to use API calls for the base system ... So there is no real information.

+1
source

Source: https://habr.com/ru/post/1541300/


All Articles