1

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");
Jack
  • 694
  • 8
  • 20
  • 3
    It depends on how you store your objects in the map. If they're a pointer to some object, the object's destructor will not be called. If they're stored by value, it will. Same goes for the insert. – divinas May 22 '19 at 08:34
  • 3
    You can try it yourself by constructing such a map. Use logging statements in the constructor and destructor to see if they are being called. – P.W May 22 '19 at 08:42
  • Anyone have any links where i can read about the expected behaviour in these cases ? – Jack May 22 '19 at 08:44
  • Haven't checked explicitly, but usually you should find anything of relevance on [cpp reference](https://en.cppreference.com/w/cpp/container/map). – Aconcagua May 22 '19 at 08:46
  • 1
    If you are willing to dig in deeper, you might get a version the [standard](https://stackoverflow.com/a/4653479/1312382) (latest draft, as being free, should be fine as well). – Aconcagua May 22 '19 at 08:50

1 Answers1

1

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.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252