C++ 当静态对象被破坏时,动态内存是否被破坏?

C++ 当静态对象被破坏时,动态内存是否被破坏?,c++,oop,memory-management,dynamic-memory-allocation,C++,Oop,Memory Management,Dynamic Memory Allocation,查看以下代码段: //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 **arg

查看以下代码段:

//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;
}
//A.h
甲级
{
无效f();
};
//A.cpp
#包括“A.h”
无效A:f()
{
地图*此地图=新地图;
//更多代码(不会出现删除)
}
//main.cpp
#包括“A.h”
int main(int argc,字符**argv)
{
物体;
object.f();
//更多代码(不会出现删除)
返回0;
}
当main()结束执行时,对象将被销毁。也会被分配给这个地图的dinamic内存破坏吗

也会被分配给这个地图的dinamic内存破坏吗

不,C++11之前的经验法则是,如果你
新建
某个东西,你以后必须
删除它

自C++11以来,我们强烈建议您使用智能指针,它以安全的方式为您处理分配/解除分配。”s文档是一个很好的起点

也会被分配给这个地图的dinamic内存破坏吗

内存泄漏,因为
对象
被销毁,它的析构函数被调用,但没有为地图调用
删除

专业提示:
delete
无论你
新建了什么
'


PS:我非常怀疑您需要动态地分配一个标准容器(如<代码> STD::MAP< /COD>),但如果您确实需要使用,则考虑使用。

不。 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;
}
void A::f()
{
  map<string, string> *ThisMap = new map<std::string, std::string>;
  //more code (a delete will not appear)
  delete ThisMap;
}
A类
{
std::map*ThisMap;
无效f();
~A();
};
void A::f()
{
ThisMap=新地图;
//更多代码(不会出现删除)
}
A::~A()
{
如果(ThisMap)删除ThisMap;
}
二,。如果ThisMap只是一个函数变量,那么您只需在使用结束时删除它,如:

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;
}
void A::f()
{
  map<string, string> *ThisMap = new map<std::string, std::string>;
  //more code (a delete will not appear)
  delete ThisMap;
}
void A::f()
{
地图*此地图=新地图;
//更多代码(不会出现删除)
删除此地图;
}
注意它的
A::f
而不是
A:f


:)

Yes
object
将被销毁并从内存中删除。但是,您在
A::f
中分配的内存将不会被释放(由您的程序释放),因此您将出现内存泄漏。经验法则:
delete
what you
new
,和
delete[]
what you
new[]
。静态对象在哪里?除此之外,动态分配标准容器通常是非常不寻常的,在大多数情况下,它确实不需要。如果出于某种原因需要,则使用例如…Ok!谢谢在这种情况下,我无法修改代码,我正在对其进行测试,CppUTest不会向我报告泄漏。我放了一个类似的代码片段,并且没有使用std::unique\u ptr。好的!谢谢在这种情况下,我无法修改代码,我正在对其进行测试,CppUTest不会向我报告泄漏。我放了一个类似的代码段,没有使用std::unique\u ptr。