Skip to content

Instantly share code, notes, and snippets.

@StarJade-Park
Created October 17, 2019 09:18
Show Gist options
  • Save StarJade-Park/6d5d5b1c73fdc94ab4bf1b637221eaab to your computer and use it in GitHub Desktop.
Save StarJade-Park/6d5d5b1c73fdc94ab4bf1b637221eaab to your computer and use it in GitHub Desktop.
#include "pch.h"
#include <iostream>
#include <memory>
#include <unordered_set>
using namespace std;
template<typename Object>
void Deleter(Object* obj)
{
delete obj;
};
class A : public std::enable_shared_from_this<A>
{
friend int main(void);
template<typename Object>
friend void Deleter(Object* obj);
static unordered_set<shared_ptr<A>> MapA;
public:
std::shared_ptr<A> MakeShared( )
{
return shared_ptr<A>(this, Deleter<A>);
}
void InsertThis( )
{
MapA.insert(dynamic_pointer_cast<A>(this->shared_from_this( )));
}
protected:
A( )
{
cout << "Construct A" << endl;
};
virtual ~A( )
{
cout << "Destruct A" << endl;
};
public:
int memberA = 10;
};
unordered_set<shared_ptr<A>> A::MapA;
class B : public A
{
friend int main(void);
template<typename Object>
friend void Deleter(Object* obj);
public:
std::shared_ptr<B> MakeSharedB( )
{
return shared_ptr<B>(this, Deleter<B>);
}
protected:
B( )
{
cout << "Construct B" << endl;
};
~B( )
{
cout << "Destruct B" << endl;
};
private:
int memberB = -10;
};
int main( )
{
A* newA = new A;
shared_ptr<A> a = newA->MakeShared( );
a->InsertThis( );
B* newB = new B;
shared_ptr<B> b = newB->MakeSharedB( );
b->InsertThis( );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment