#include <iostream>
#include <string>
#include <vector>
struct Vertex
{
float x, y, z;
Vertex(float x, float y, float z)
: x(x), y(y), z(z)
{
}
Vertex(const Vertex& vertex)
: x(vertex.x), y(vertex.y), z(vertex.z)
{
std::cout << "Copied" << std::endl;
}
};
std::ostream& operator<<(std::ostream& stream, const Vertex& vertex)
{
stream << vertex.x << ", " << vertex.y << ", " << vertex.z;
return stream;
}
void Function(const std::vector<Vertex>& vertices)
{
}
int main()
{
std::vector<Vertex> vertices;
// optimize one
vertices.reserve(3);
vertices.push_back(Vertex(1, 2, 3 ));
vertices.push_back(Vertex(4, 5, 6 ));
vertices.push_back(Vertex(7, 8, 9 ));
// optimize two
vertices.emplace_back(Vertex(1, 2, 3 ));
vertices.emplace_back(Vertex(1, 2, 3 ));
for (int i = 0; i < vertices.size(); i++)
std::cout << vertices[i] << std::endl;
// Clear the second
vertices.erase(vertices.begin() + 1);
for (Vertex v : vertices)
std::cout << v << std::endl;
for( Vertex& v : vertices)
std::cout << v << std::endl;
// Clear Vertices
vertices.clear();
std::cin.get();
}
发生拷贝的地方:
使用 push_back 时, vector会逐渐变大, 1 --> 2 --> 4 --> 8
从main函数的堆栈里构建对象,然后拷贝到vector中
push_back 1 次, 复制 1 次 1
push_back 2 次, 复制 3 次 2 + 1
push_back 3 次, 复制 6 次 3 + 3
push_back 4 次, 复制 7 次 4 + 3