std::map::clear and elements' destructors

10,146

Solution 1

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/

Solution 2

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.

Share:
10,146

Related videos on Youtube

Vikas Putcha
Author by

Vikas Putcha

Enthusiastic developer.

Updated on July 12, 2022

Comments

  • Vikas Putcha
    Vikas Putcha almost 2 years

    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.

    • Kiril Kirov
      Kiril Kirov
      How do you "notice" std::string destructor?
  • Vikas Putcha
    Vikas Putcha over 11 years
    Yes I agree with your code, but I was aiming at std::string objects rather than user defined objects. Thanks for your time Chris.
  • Vikas Putcha
    Vikas Putcha over 11 years
    Some how I missed it, but I could see my break point being hit at std::string destructor, and yes indeed the call stack came from std::allocator. Thanks for your time John.
  • Vikas Putcha
    Vikas Putcha over 11 years
    True, but i was looking for std::string though, my question got answered by the below comment, the reference link served the purpose to re-check my understanding, as it improved assurance level in my thinking.