Std :: map, polymorphism and deletion

I have a problem using a C ++ map to store pointers to a base class and some derived class.

Let me explain the rather long but simple code:

#include <map> #include <iostream> struct foo{ int dummy[4]; }; struct bar{ int additionnal[4]; }; class Base { private: struct foo *_internal_structure; public: Base() { _internal_structure = new struct foo; } ~Base() { delete _internal_structure; std::cout << "Base DTOR\n"; } }; class Derived: public Base { private: struct bar *_additional_structure; public: Derived() { _additional_structure = new struct bar; } ~Derived() { delete _additional_structure; std::cout << "Derived DTOR\n"; } }; int main(int argc, char *argv[]) { std::map<int, Base*> my_map; Base *to_add = new Base(); Derived *derived_to_add = new Derived(); my_map[1] = to_add; my_map[2] = derived_to_add; // works, derived class, but object gets sliced /// clear hash map /// std::map<int, Base*>::const_iterator iter; for(iter = my_map.begin(); iter != my_map.end(); ++iter) { delete (*iter).second; } return 0; } 

Startup Result:

 Base DTOR Base DTOR 

So, when I insert the pointer of the Derived class into my map, the base object is considered as a base class; therefore, the called destructor is one of the base class, not the Derived class. Valgrind confirms that I lose 16 bytes every time.

In addition, I cannot use Boost shared_ptr ( I saw some mention of this here ), and the built-in architecture that I use does not support C ++ and RTTI exceptions (which in my case causes some unusual calls and other bad things) ( edit : not applicable).

Do you know how I can fix this behavior?

+4
source share
2 answers

Where is your virtual destructor ??? !!!

Read it and never forget. In fact, you just violated one of the 10 C ++ commands ... :))

+13
source

Your destructor in any base class must be virtual .

Otherwise, it is impossible to determine at runtime which destructor should actually be called when subclasses reference a pointer to their base class.

+6
source

All Articles