dynamic memory allocation 在堆里面申请空间
- new
- new int; // 分配一块 int 空间
- new Stash; // 分配Stash对象的空间 然后调用构造函数初始化
- new int[10] // 分配10个int 空间
- delete // 给它一个地址
- delete p; //
- delete[] p;
相当于c中malloce和free
任何运算都有结果,new操作返回的是地址
动态制造对象。 new 带着[ ], delete 也要带着[]。
delete p所指的对象时候,析构函数先被调用,然后空间被回收。
new and delete
-
new is the way to allocate memory as a program runs. Pointers become the only access to that memory
-
delete enables you to return memory to the memory pool when you are finished with it
dynamic arrays
int * psome = new int [10]; // 动态申请数组
- the new operator returns the address of the first element of the block
delete [] psome; // []释放,10个析构都会被调用, 不带[]只有一个被析构
- the presence of the brackets tells the program that it should free the whole array,not just the element


tips for new an delete
-
don't use delete to free memory that new didn't allocate
-
don't use delete to free the same block of memory twice in succession(连续)
-
use delete[] if you used new [] to allocate an array
-
use delete (no brackets) if you used new to allocate an array
-
it's safe to apply delete to the null pointer (noting happens)

new了对象但是不delete,因为我们现在的程序都是跑一下,我们的操作系统都是多进程,程序每次运行都是一个进程,操作系统给分配了虚拟空间,当程序结束后,空间会被回收,即使申请了内存没有释放,打开文件没有关闭,但是程序结束后都结束了。
但是如果程序要一直运行,那么会存在内存泄漏问题。

被折叠的 条评论
为什么被折叠?



