c++ - boost shared pointer constructor destructor -
the following code
struct base { public: base() { std::cout<<"base ctr"; } ~base() { std::cout<<"base dtr"; } }; struct derived : base { derived() { std::cout<<"derived ctr"; } ~base() { std::cout<<"derived dtr"; } }; int main() { base* b = new derived; delete b; }
gives me following output :
base ctr derived ctr base dtr
the solution make base destructor virtual.
however when use boost smart pointers without virtual base destructor. different output.
int main() { boost::shared_ptr<base> b = boost::make_shared<derived>(); }
the output is
base ctr derived ctr derived dtr base dtr
how boost shared_ptr able achieve without affecting(i'm assuming) base , derived classes.
how scale multiple level inheritance, i.e base points dervderv dervderv inherited derv.
edit:
most answers tell me "magic" happens in make_shared. same behaviour following code
boost::shared_ptr<base> ptr(new derived);
a solution implemented using normal function pointers:
#include <iostream> #include <boost/shared_ptr.hpp> #include <boost/make_shared.hpp> #include <typeinfo> using namespace std; struct base{ base(){ cout<<"base ctor."<<endl; } ~base(){ cout<<"base dtor."<<endl; } }; struct derv: base{ derv():base(){ cout<<"derv ctor."<<endl; } ~derv(){ cout<<"derv dtor."<<endl; } }; typedef void (*del)(void*); template<typename u> void deleter(void* ptr) { delete static_cast<u*>(ptr); } template<typename t> struct smartptr{ t* memptr; del func; template<typename u> smartptr(u* p): memptr(p) { func = deleter<u>; } ~smartptr(){ func(memptr); } }; int main() { //case 1 smartptr<base> ptrsmart1(new derv()); //case 2 smartptr<base> ptrsmart2(new base()); //case 3 smartptr<derv> ptrsmart3(new derv()); return 0; }
Comments
Post a Comment