I am observing strange behaviour of std::map::clear(). This method is supposed to call element’s destructor when called, however memory is still accessible after call to clear().
For example:
struct A { ~A() { x = 0; } int x; }; int main( void ) { std::map< int, A * > my_map; A *a = new A(); a->x = 5; my_map.insert( std::make_pair< int, *A >( 0, a ) ); // addresses will be the same, will print 5 std::cout << a << ' ' << my_map[0] << ' ' << my_map[0]->x << std::endl; my_map.clear(); // will be 0 std::cout << a->x << std::endl; return 0; }
The question is, why is variable a still accessible after its destructor was called by map::clear()? Do I need to write delete a; after calling my_map.clear() or is it safe to overwrite the contents of a?
Thanks in advance for your help, sneg
std::map does not manage the memory pointed to by the pointer values – it’s up to you to do it yourself. If you don’t want to use smart pointers, you can write a general purpose free & clear function like this:
And use it:
;