Skip to content

Instantly share code, notes, and snippets.

@areinull
Created July 9, 2014 09:19
Show Gist options
  • Save areinull/229c810938c1e246940f to your computer and use it in GitHub Desktop.
Save areinull/229c810938c1e246940f to your computer and use it in GitHub Desktop.
Self owned class using std::shared_ptr. Destroys itself after work() is done.
#include <memory>
#include <iostream>
#include <unistd.h>
#include <thread>
using namespace std;
class a: public std::enable_shared_from_this<a>
{
std::shared_ptr<a> self;
public:
//a() {cout << "ctor" << endl;}
a(): self(this) {cout << "ctor" << endl;}
~a() {cout << "dtor" << endl;}
std::shared_ptr<a> getPtr() {return shared_from_this();}
void destroy() {self.reset();}
void work() {cout << "sleep" << endl; sleep(3); cout <<"wake"<<endl; destroy();}
};
int main() {
cout << "1" << endl;
a *tmp = new a;
std::shared_ptr<a> pa = tmp->getPtr();
tmp = 0;
cout << "2" << endl;
std::thread th(std::bind(&a::work, pa.get()));
pa.reset();
cout << "3" << endl;
th.join();
cout << "4" << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment