Skip to content

Instantly share code, notes, and snippets.

@erwinv
Created June 20, 2019 09:58
Show Gist options
  • Save erwinv/fd875bf32aecd7ea5aa2971768955d31 to your computer and use it in GitHub Desktop.
Save erwinv/fd875bf32aecd7ea5aa2971768955d31 to your computer and use it in GitHub Desktop.
Deferred call to weak bound member function
#include <functional>
#include <iostream>
#include <memory>
using namespace std;
class A : public enable_shared_from_this<A>
{
public:
A() : data_(make_unique<int>(0))
{
cout << "A::A() ctor: " << hex << this << endl;
}
~A()
{
cout << "A::~A() dtor: " << hex << this << endl;
}
void handle(int data) {
*data_ = data;
cout << "A::handle() : " << hex << this << ", data: " << dec << *data_ << endl;
}
std::function<void()> deferredHandle(int data)
{
cout << "A::deferredHandle() : " << hex << this << ", arg=" << dec << data << endl;
// raw pointer => segfault
// return [instance=this, data]{
// instance->handle(data);
// };
// shared pointer => object's lifetime is extended by deferred call
// return [instance=shared_from_this(), data] {
// instance->handle(data);
// };
// weak pointer => deferred call is non-owning (weak ref)
return [instance=weak_ptr<A>(shared_from_this()), instanceId=this, data] {
if (auto lockedInstance = instance.lock())
lockedInstance->handle(data);
else
cout << "Referred instance was already destroyed: " << hex << instanceId << endl;
};
}
private:
unique_ptr<int> data_;
};
int main()
{
auto a = make_shared<A>();
a->handle(1);
a->handle(2);
a->handle(3);
auto deferred4 = a->deferredHandle(4);
auto deferred5 = a->deferredHandle(5);
auto deferred6 = a->deferredHandle(6);
deferred4();
deferred5();
a.reset();
deferred6();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment