Smart Pointers and 'delete'

Started by
12 comments, last by Nitage 18 years, 7 months ago
If the destructor is not virtual and you call delete on the final object (the most derived class), everything will be called.

But if it's not virtual and you call delete on one of the base class, it will not execute the destructor of the derived classes.

Basically if it's a base class and destructor is public, make it virtual.
Advertisement
Quote:Original post by Blaster
But if it's not virtual and you call delete on one of the base class, it will not execute the destructor of the derived classes.


The behaviour is undefined, never take trip to the land of undefined....

Quote:Original post by Blaster
Basically if it's a base class and destructor is public, make it virtual.


Thats being abit hasty, better advice would be:

if you intend on invoking delete on pointers to base types then make the base type's destructor (pure) virtual.
snk_kid: Your improvements on my comments are very good. You made me think, thank you.
But hey, I must be a hasty fellow :)

++rank
struct int_struct{    int i;};template<class T>class smart_ptr{public:    explicit smart_ptr(T* value);    T& operator*(){return *_value;}//add null checking before using    T* operator->(return _value;)       //instead of:    operator T* (){return _value;}    //you want something like this:    const T* get()const{return _value;}    //and possibly    T* release(){/*something a little more complicated*/}};//Now:smart_ptr<int_struct> a = smart_ptr<int_struct>(new int_struct);delete a;//compiler errordelete a.get();//compiler errorstd::cout << a->i;//finea->i = 5;//fine*a.i = 5;//fine


That does what you want. You obviously need to add the rest of the implementation.

This topic is closed to new replies.

Advertisement