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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
#include <iostream>
#include <vector>
struct Vertex
{
float x, y, z;
Vertex(float x, float y, float z) : x(x), y(y), z(z) {}
Vertex(const Vertex& other) : x(other.x), y(other.y), z(other.z)
{
std::cout << "Copied Vertex(" << x << ", " << y << ", " << z << ")" << std::endl;
}
Vertex(Vertex&& other) noexcept : x(other.x), y(other.y), z(other.z)
{
std::cout << "Moved Vertex(" << x << ", " << y << ", " << z << ")" << std::endl;
}
};
std::ostream& operator<<(std::ostream& ostream, const Vertex& vertex)
{
ostream << vertex.x << ", " << vertex.y << ", " << vertex.z;
return ostream;
}
void DemonstrateReallocation()
{
std::cout << "=== Without reserve ===" << std::endl;
std::vector<Vertex> vertices;
std::cout << "Initial capacity: " << vertices.capacity() << std::endl;
vertices.push_back(Vertex(1, 2, 3));
std::cout << "After 1st push_back, capacity: " << vertices.capacity() << std::endl;
vertices.push_back(Vertex(4, 5, 6));
std::cout << "After 2nd push_back, capacity: " << vertices.capacity() << std::endl;
vertices.push_back(Vertex(7, 8, 9));
std::cout << "After 3rd push_back, capacity: " << vertices.capacity() << std::endl;
/*
分析输出结果:
1. Vector首先在当前栈上创建临时对象,然后移动到Vector内存中,会输出1次Moved
2. 当Vector当前容量不足以存储新加入的元素时,会重新分配Vector内存,
也就是在当前栈上重新创建一个Vector,然后将旧的Vector中的元素Copied到新的Vector中,
然后再把新的Vector移动到实际的Vector内存中去,这就是为什么会输出3次Copied的原因
*/
}
int main()
{
DemonstrateReallocation();
}
|