Created
July 21, 2012 22:23
-
-
Save Olwaro/3157398 to your computer and use it in GitHub Desktop.
Fun with C++11 smart ptr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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