Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map::clear and elements' destructors

Does destructor get called on std::map elements when std::map::clear is used?

I tried to debug for std::map<string,string> but could not see std::string destructor getting invoked. Can any one please help my understanding?

Documentation states it gets called, but I could not notice it.

like image 781
Vikas Putcha Avatar asked Nov 17 '12 07:11

Vikas Putcha


2 Answers

Documentation is right, it does get called.

The destruction will be done by the method std::allocator<T>::deallocate(). Trace through that in your debugger.

http://www.cplusplus.com/reference/std/memory/allocator/

like image 192
john Avatar answered Oct 07 '22 04:10

john


The destructor does get called. Here is an example to illustrate:

#include <iostream>
#include <map>

class A
{
 public:
  A() { std::cout << "Constructor " << this << std::endl; }
  A(const A& other) { std::cout << "Copy Constructor " << this << std::endl; }
  ~A() { std::cout << "Destructor " << this <<std::endl; }
};

int main()
{
  std::map<std::string, A> mp;

  A a;

  mp.insert(std::pair<std::string, A>("hello", a));
  mp.clear();

  std::cout << "Ending" << std::endl;
}

This will report an output similar to this:

Constructor 0xbf8ba47a
Copy Constructor 0xbf8ba484
Copy Constructor 0xbf8ba48c
Copy Constructor 0x950f034
Destructor 0xbf8ba48c
Destructor 0xbf8ba484
Destructor 0x950f034
Ending
Destructor 0xbf8ba47a

So, you can see that the destructors get called by the calling the clear function.

like image 31
Chris Mansley Avatar answered Oct 07 '22 05:10

Chris Mansley