Using shared_from_this() in constructor
Nov 17, 2016 at 8:38pm UTC
Hi all,
As you know it is not possible to use the std::enable_shared_from_this<T> and shared_from_this() pair from the constructor of an object since a shared_pointer<T> containing the class is not yet in existance. However, I really would like this functionality. I have attempted my own system and it seems to be working OK.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
#ifndef KP_MEMORY_H
#define KP_MEMORY_H
#include <memory>
namespace kp
{
template <class T>
void construct_deleter(T *t)
{
t->~T();
free(t);
}
template <class T, typename ... Params>
std::shared_ptr<T> make_shared(Params&&... args)
{
std::shared_ptr<T> rtn;
T *t = (T *)calloc(1, sizeof (T));
rtn.reset(t, construct_deleter<T>);
t->_construct_pself = &rtn;
t = new (t) T(std::forward<Params>(args)...);
t->_construct_pself = NULL;
t->_construct_self = rtn;
return rtn;
}
template <class T>
class enable_shared_from_this
{
public :
std::shared_ptr<T> *_construct_pself;
std::weak_ptr<T> _construct_self;
std::shared_ptr<T> shared_from_this()
{
if (_construct_pself)
{
return *_construct_pself;
}
else
{
return _construct_self.lock();
}
}
};
}
#endif
Can anyone spot any flaws in this logic?
As it stands I can use it as so:
std::shared_ptr<Employee> emp = kp::make_shared<Employee>("Karsten" , 30);
and in the Employee constructor:
1 2 3 4
Employee::Employee(std::string name, int age)
{
Dept::addEmployee(shared_from_this());
}
Before I commit this to a relatively large codebase, I would really appreciate some ideas or feedback from you guys.
Thanks!
Last edited on Nov 17, 2016 at 8:40pm UTC
Topic archived. No new replies allowed.