Skip to content

Instantly share code, notes, and snippets.

@alekfrohlich
Created December 6, 2019 22:16
Show Gist options
  • Save alekfrohlich/c87606a303733510f0c8d11b5cbc469f to your computer and use it in GitHub Desktop.
Save alekfrohlich/c87606a303733510f0c8d11b5cbc469f to your computer and use it in GitHub Desktop.
vector pitfalls
//file: optm_vec.cc
#include <iostream>
#include <vector>
struct Vertex {
float x, y, z;
Vertex(float x, float y, float z)
: x(x), y(y), z(z)
{
std::cout << "normal construction!" << std::endl;
}
Vertex(const Vertex & other)
: x(other.x), y(other.y), z(other.z)
{
std::cout << "copy!" << std::endl;
}
};
int main(void) {
std::vector<Vertex> vertices;
// avoid resizing each time we push_back a new vertex.
vertices.reserve(3); // comment this to see what happens
// if we instead did push_back, then we'd first have
// to place the Vertex on the stack and later add it to
// vector with a copy for each push_back. emplace_back recieves
// Vertex's parameters and instantiates it directly inside vector.
vertices.emplace_back(1,2,3);
vertices.emplace_back(4,5,6);
vertices.emplace_back(7,8,9);
// swap comments with this one to see what happens
// vertices.push_back(Vertex(1,2,3));
// vertices.push_back(Vertex(4,5,6));
// vertices.push_back(Vertex(7,8,9));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment