c++ vector push_back() vs emplace_back

std::vector::push_back()

Appends the given element value to the end of the container.

  • The new element is initialized as a copy of value.
  • value is moved into the new element.

If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated. (Cite from: cppreference.com)


Example

Firstly, if we have a class String, then we can use this class to test the push_back() functions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

#include <cstring>
#include <vector>
class {
public:
string() : buf(new char[1]) {
std::cout << "default" << std::endl;
buf[0] = '