[英]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_ptr
和std::shared_ptr
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.