Skip to content

Instantly share code, notes, and snippets.

@waveacme
Created May 11, 2016 08:26
Show Gist options
  • Save waveacme/9114cb1e534da2f476a8cbc8ed09dcd9 to your computer and use it in GitHub Desktop.
Save waveacme/9114cb1e534da2f476a8cbc8ed09dcd9 to your computer and use it in GitHub Desktop.
c++11 shared_ptr example
//g++ -std=c++0x ptr.cpp
#include <cstdio>
#include <cstring>
#include <vector>
#include <memory>
using namespace std;
class Integer {
int n;
public:
Integer(int n) : n(n) {}
~Integer() { printf("deleting %d\n", n); }
int get() const { return n; }
};
typedef shared_ptr<Integer> IntegerPtr;
vector<IntegerPtr> v;
int foo()
{
shared_ptr<Integer> a(new Integer{ 10 });
v.push_back(a);
shared_ptr<Integer> b(new Integer{ 20 });
v.push_back(b);
shared_ptr<Integer> c = a;
shared_ptr<Integer> d(new Integer{ 30 });
v.push_back(d);
shared_ptr<Integer> e = b;
a = d;
b = shared_ptr<Integer>(new Integer(40));
v.push_back(b);
shared_ptr<Integer> f = c;
b = f;
}
void clear()
{
vector<IntegerPtr>::iterator i;
for (i = v.begin(); i != v.end();) {
printf("erase %d\n", (*i)->get());
i = v.erase(i);
}
}
int main()
{
printf("hello\n");
foo();
printf("hi\n");
clear();
printf("bye\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment