So we have (pseudo code):
class A
{
A(shared_ptr parent){}
}
class B
{
A *a;
B()
{
a = new A(boost::shared_ptr(this));
}
}
Is it possible to do such thing with shared_ptr in C++ and how to do it in real C++ code?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You need
enable_shared_from_this:(This is for C++0x; Boost should work similarly.)
Just making a shared pointer from
thisis tricky because you might shoot your own foot off. Inheriting fromenable_shared_from_thismakes this easier.Word of warning: Your construction with the naked
Apointer seems to defeat the purpose of using resource-managing classes. Why not makeainto a smart pointer, too? Maybe aunique_ptr?