Jack
Jack

Reputation: 744

Destructor call when an object is removed/erased from a map

I have one doubt, i have a map which stores class object against some arbitrary strings now when i delete any element from map (using erase/remove api) will the destructor of class object stored in that element be called ? Also When i insert the class object is my map against a string value, the ctor of class will be called and a copy of object will be created in map. Is my understanding correct here? Any links explaining these scenarios would be helpful.

Will below code call copy constructor of class Myclass? I tried putting in a cout in MyClass copy ctor but didn't see it in output.

Note : The objects are stored by value in map.

QMap<QString, MyClass> testMap;
MyClass obj;
testMap.insert("test", obj);
testMap.remove("test");

Upvotes: 1

Views: 1274

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 149075

As your objects are stored by value, you will store new instances in the map. That means that a ctor will be called at insertion time. On most insertions, a copy/move ctor will be used, but a different ctor can be selected with the emplace... methods. And the default ctor is used when you create default values in a vector by giving it an initial size or by extending it.

The same, when an object is removed or erased from the map, it is destroyed so its dtor will be called. No special magic about that: the usual rules for object lifetime are applied here.

Upvotes: 1

Related Questions