销毁静态对象时动态内存是否被销毁?

Is dynamic memory destroyed when static object is destroyed?

查看以下代码片段:

//A.h
class A
{
  void f();
};

//A.cpp
#include "A.h"

void A:f()
{
  map<string, string> *ThisMap = new map<string, string>;

  //more code (a delete will not appear)
}

//main.cpp
#include "A.h"

int main( int argc, char **argv )
{
  A object;

  object.f();

  //more code (a delete will not appear)

  return 0;
}

当main()结束执行时,对象将被销毁。分配给 ThisMap 的动态分配内存也会被销毁吗?

Would be destroyed dinamic allocated memory asigned to ThisMap too?

不,C++11 之前的经验法则是,如果你 new 某些东西,你必须在以后 delete 它。

从 C++11 开始,我们强烈建议您使用 智能指针 ,它以安全的方式为您处理 allocation/deallocation。 std::unique_ptr 的文档是一个很好的起点。

Would be destroyed dinamic allocated memory asigned to ThisMap too?

!

你有内存泄漏,因为 object 被销毁,它的析构函数被调用,但没有为你的地图调用 delete

专业提示:delete无论您new使用什么,当您完成它时。


PS:我很怀疑你需要动态分配一个标准容器(比如std::map),但是如果你真的确定你需要使用,那么考虑使用std::unique_ptr.

没有。
1.如果你想让ThisMap成为A的数据字段,你必须声明并实现你自己的析构函数,所以你的代码应该是这样的:

class A
{
  std::map<std::string, std::string> *ThisMap;
  void f();
  ~A();
};

void A::f()
{
  ThisMap = new map<std::string, std::string>;

  //more code (a delete will not appear)
}
A::~A()
{
  if(ThisMap) delete ThisMap;
}

2。如果 ThisMap 只是一个函数变量,那么你只需要在使用结束时删除它,如:

void A::f()
{
  map<string, string> *ThisMap = new map<std::string, std::string>;
  //more code (a delete will not appear)
  delete ThisMap;
}

请注意它是 A::f 而不是 A:f
:)