简体   繁体   English

在这种情况下,是否需要清空地图的内容,以避免内存泄漏

[英]Do I need to empty the contents of a map in this case to avoid memory leaks

Suppose I have a class as such 假设我有这样的课程

struct fooBar
{
   std::map<int, std::shared_ptr<foo> > mp_items;
   ~fooBar()
   { /* Destructor does nothing */ }
};

In the above case does the destructor have to mention mp_items.clear() or is it safe without that ?` 在上述情况下,析构函数是否必须提及mp_items.clear()否则没有安全性吗?

Since your map is containing shared_ptr, you don't need to take care of memory management. 由于您的地图包含shared_ptr,因此您无需进行内存管理。 They will automatically be deleted when your map goes out of scope. 当您的地图超出范围时,它们将被自动删除。 One important thing to note over here is elements would be deleted only if there reference count reaches 0. 这里要注意的一件事是,只有当引用计数达到0时,元素才会被删除。

From cppreference : 来自cppreference

 std::map::~map() 

Destructs the container. 破坏容器。 The destructors of the elements are called and the used storage is deallocated. 调用元素的析构函数,并释放已使用的存储。

So no, there is no need to call clear() because the map's destructor does it for you. 因此,不需要,无需调用clear()因为地图的析构函数会为您执行此操作。

The only case in which you'd ever have to deallocate memory in the destructor is if you allocated a data member with new / new[] and want its life to end when the object goes out of scope. 唯一必须在析构函数中释放内存的情况是,如果您使用new / new[]分配了一个数据成员,并希望当对象超出范围时其生命期结束。 In that case you would call delete / delete[] in the destructor. 在这种情况下,您可以在析构函数中调用delete / delete[]

However, note that there are memory management containers in the standard library that do it for you, like std::unique_ptr and std::shared_ptr among others. 但是,请注意,标准库中有一些内存管理容器可以为您完成此工作,例如std::unique_ptrstd::shared_ptr等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在这种情况下我是否需要以某种方式释放内存? - Do I need to free the memory in this case somehow? 是否必须使用Delete以避免内存泄漏? 我已经使用new来分配结构实例 - Do I have to use delete to avoid memory leaks? I have used new to allocate the structure instances 我如何正确处理垃圾回收并通过自定义对象指针的集合避免内存泄漏……? - How do I properly handle garbage collection and avoid memory leaks with a collection of custom object pointers…? C ++:我什么时候需要考虑可能的内存泄漏? - C++: When do I need to think about possible memory leaks? 我对 memory 泄漏有什么不明白的地方? - What do I not understand about memory leaks? 如何停止内存泄漏? - How do I stop memory Leaks? 在这种特殊情况下,我是否需要共享内存中的原子类型? - Do I need an atomic type in shared memory in this particular case? 为什么在正确释放 memory 时会出现 memory 泄漏? - Why do I get memory leaks while properly deallocating memory? 映射类导致内存泄漏 - map class causes memory leaks 2D std :: vector替换值 - 需要删除以避免内存泄漏? - 2D std::vector replace values - need for delete to avoid memory leaks?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM