Last active
December 10, 2015 04:08
-
-
Save fthomas/4379321 to your computer and use it in GitHub Desktop.
See http://timepit.eu/~frank/blog/2013/03/enable_weak_from_this/ for more information.
This file contains hidden or 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 <memory> | |
template<class T> | |
struct enable_weak_from_this { | |
enable_weak_from_this() : ref_{static_cast<T*>(this), nopDeleter} {} | |
std::weak_ptr<T> weak_from_this() const { | |
return ref_; | |
} | |
private: | |
static void nopDeleter(void*) {} | |
std::shared_ptr<T> ref_; | |
}; |
This file contains hidden or 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 "enable_weak_from_this.h" | |
struct B; | |
struct A : enable_weak_from_this<A> { | |
void hello() const { std::cout << "A::hello called\n"; } | |
B* createB() const; | |
}; | |
struct B { | |
B(const std::weak_ptr<A>& creator) : creator_{creator} {} | |
void callHello() const { | |
if (auto a = creator_.lock()) { | |
a->hello(); | |
} else { | |
std::cout << "creator_ has been destroyed\n"; | |
} | |
} | |
private: | |
std::weak_ptr<A> creator_; | |
}; | |
B* A::createB() const { | |
return new B{weak_from_this()}; | |
} | |
int main(int argc, char* argv[]) { | |
auto a = new A; | |
auto b = a->createB(); | |
b->callHello(); | |
delete a; | |
b->callHello(); | |
delete b; | |
} | |
// $ g++ -std=c++11 test.cpp | |
// $ ./a.out | |
// A::hello called | |
// creator_ has been destroyed |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment