Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#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_;
};
#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
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.