Skip to content

Instantly share code, notes, and snippets.

@hi2p-perim
Last active August 29, 2015 14:18
Show Gist options
  • Save hi2p-perim/014c855224716d6f5687 to your computer and use it in GitHub Desktop.
Save hi2p-perim/014c855224716d6f5687 to your computer and use it in GitHub Desktop.
A notice on utilizing pointer to vector elements
#include <iostream>
#include <vector>
#include <memory>
struct A { int v; };
struct B { const A* a; };
int main()
{
// NG. Taking raw pointer of an element of the vector.
// The pointer to the element is changed in the reallocation in push_back.
#if 0
std::vector<A> v;
std::vector<B> v2;
for (int i = 0; i < 10; i++)
{
B b;
{
A a;
a.v = i;
v.push_back(std::move(a));
b.a = &v.back();
}
v2.push_back(std::move(b));
}
for (int i = 0; i < 10; i++)
{
std::cout << v2[i].a->v << std::endl;
}
#endif
// OK. Utilizing std::unique_ptr.
#if 1
std::vector<std::unique_ptr<A>> v;
std::vector<B> v2;
for (int i = 0; i < 10; i++)
{
B b;
{
std::unique_ptr<A> a(new A);;
a->v = i;
b.a = a.get();
v.push_back(std::move(a));
}
v2.push_back(std::move(b));
}
for (int i = 0; i < 10; i++)
{
std::cout << v2[i].a->v << std::endl;
}
#endif
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment