Skip to content

Instantly share code, notes, and snippets.

@Olwaro
Created July 21, 2012 22:23
Show Gist options
  • Save Olwaro/3157398 to your computer and use it in GitHub Desktop.
Save Olwaro/3157398 to your computer and use it in GitHub Desktop.
Fun with C++11 smart ptr
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
class Stuff
{
int val;
public:
Stuff(int v):val(v){cout << "Stuff created : " << this << endl;}
~Stuff()
{
cout << "Stuff deleted : " << this << endl;
}
friend ostream& operator<<(ostream& os, const Stuff& s)
{
os << "Show :" << &s;
return os;
}
};
void shared_play()
{
auto www = make_shared<Stuff>(42);
shared_ptr<Stuff> mmm = www;
vector<decltype(www)> vec(3);
cout << "WWW " << www << endl;
cout << "MMM " << mmm << endl;
vec[0] = www;
www = nullptr;
mmm = nullptr;
vec.clear();
}
void unique_play()
{
unique_ptr<Stuff> www(new Stuff(42));
unique_ptr<Stuff> mmm(std::move(www));
vector<decltype(www)> vec(3);
//vec[0] = std::move(mmm);
mmm = nullptr;
cout << "WWW " << &(*www) << endl;
cout << "MMM " << &(*mmm) << endl;
}
int main()
{
//shared_play();
unique_play();
cout << "--- END ---" << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment