0

I have a question, if i cleared map1, it will also clear map2 or there will be memory leaks? here is the code.

struct mystruct
{
std::map<int, double> map2;
};

std::map<int, mystruct> map1;
map1.clear();

Thanks.

EDIT: if no memory leaks then both map1 and map2 will be cleared when i clear map1 ?

Badr Timo
  • 1
  • 1
  • No memory leaks in the above snippet. You aren't using `new` to start with nor are you using circularly dependent smart pointers. – Jason Jul 02 '22 at 04:47
  • thanks for fast answer, I edited the question can you take a look please. – Badr Timo Jul 02 '22 at 04:52
  • 1
    When you write `map1.clear()`, then `map1` will be cleared. Meaning the elements inside it are removed. I think you're confusing `map1` and `map2`. Note, `map2` is a data member. When the object of type `mystruct` goes out of scope(or destroyed) then the data member will also be destroyed. You don't have to worry about memory leak here. – Jason Jul 02 '22 at 04:55
  • No `map2` will exist after `map1` is cleared. But (like everyone else) there are no memory leaks here. – john Jul 02 '22 at 05:53
  • @BadrTimo Also (this seems to be where you are confused). There will be no memory leaks even **without** clear. You don't have to clear maps to avoid memory leaks, they look after their own memory. – john Jul 02 '22 at 05:54

0 Answers0