mickeyj
mickeyj

Reputation: 101

Deleting pointers and map in destructor

Suppose a class contains pointers and map of strings. In the destructor, apart from deleting the pointers, should we also clear the map or would this be automatically done?

Upvotes: 0

Views: 385

Answers (1)

Bathsheba
Bathsheba

Reputation: 234785

If you have a member variable like std::map<> (that you've stack-allocated) then you can rely on its destructor when your class destructs. The standard mandates that std::map will release all its memory once it's destroyed.

If you declare it as a pointer and you have used new, then you ought to use delete in your destructor. Just be careful not to have any exceptions thrown in your destructor as that will cause memory faults.

Upvotes: 2

Related Questions