当静态对象被破坏时,是动态内存而破坏的

Is dynamic memory destroyed when static object is destroyed?

本文关键字:动态 内存 静态 对象      更新时间:2023-10-16

查看以下代码段:

//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(main()结束IT执行时,对象将被破坏。会被摧毁的dinamic分配的记忆也将其降低到此图吗?

也会被销毁的迪纳米人分配的记忆也被划分为该图吗?

您有内存泄漏,因为object被销毁,其破坏者被调用,但没有delete用于您的地图。

pro-tip: delete无论您使用什么 new',完成后。


ps:我非常怀疑您需要动态分配标准容器(例如std::map),但是如果您真的确定需要使用,请考虑使用std::unique_ptr

也会被销毁的迪纳米人分配的记忆也被划分为该图吗?

否,C 11之前的经验法则是,如果您new某物,则必须以后delete

自C 11以来,非常鼓励您使用智能指针,它以安全的方式为您处理分配/交易。std::unique_ptr的文档是一个很好的起点。

no。
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。如果此图只是一个函数变量,因此您只需要在使用结束时将其删除,例如:

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
:)