当静态对象被破坏时,是动态内存而破坏的
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(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
:)
相关文章:
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 开放 CV 中的动态内存分配,用于视频处理
- 为什么类和 main() 函数中也有动态内存分配
- 在没有动态内存的世界中,我是否需要虚拟析构函数?
- c++ 动态内存 堆栈中的分配
- 给定特定内存地址的数组的动态内存分配
- 释放动态内存时C++错误
- 我刚刚了解了C++中的动态内存分配
- 无法删除布尔动态内存分配
- 有没有办法找到动态内存大小,比如大小?
- 我在 2D 数组的动态内存分配中遇到了一些奇怪的代码C++? 请解释一下这是什么?
- 具有对齐存储的动态内存分配
- 指向数组unique_ptr在调用 release() 后会自动释放动态内存,这是真的吗?
- 在cpp中使用boost-python的python代码是否进行动态内存分配
- 我应该在这个程序中使用静态内存分配还是动态内存分配
- C++ 模板函数中的动态内存分配
- 指向动态内存中结构中的变量时出现问题
- C++具有动态内存分配的 constexpr 函数
- 动态内存分配错误
- 按引用传递和动态内存分配之间的区别是什么