new / new []是否应与delete / delete []相匹配? [英] Should new/new[] match delete/delete[]?
问题描述
我知道,当我们使用new / new []分配内存时,应该分别使用delete / delete []释放内存。
这里问题是
我可以使用delete []释放由new分配的内存吗?
例如,
int * pInt3 = new int;
delete [] pInt3;
pInt3 = NULL;
T * pT3 =新的T;
delete [] pT3;
pT3 = NULL;
谢谢
否,您应该将非数组形式的 new
与非数组 delete
匹配,
请参见关于Freestore Management的C ++ FAQ Lite部分
这特别好: http://www.parashift.com/c%2B%2B-faq-lite/freestore-mgmt .html#faq-16.12
[16.12]如果删除通过新T [n]分配的数组时忘记了[]怎么办? / p>
所有生命都陷入了灾难性的终结。
在新T [n]与新的T [n]之间建立联系是程序员的责任,而不是编译器的责任。 delete [] p正确。如果弄错了,编译器将不会生成编译时消息或运行时错误消息。堆损坏可能是结果。或更糟。您的程序可能会死。
I knew that when we allocate memory by using new/new[], then we should release the memory by using the delete/delete[] respectively.
Here is the question,
Can I use delete[] to release the memory allocated by new?
For example,
int *pInt3 = new int;
delete [] pInt3;
pInt3 = NULL;
T *pT3 = new T;
delete [] pT3;
pT3 = NULL;
Thank you
No, you should match the non-array form of new
with non-array delete
, and likewise for the array forms.
See the C++ FAQ Lite section on Freestore Management
This is especially good: http://www.parashift.com/c%2B%2B-faq-lite/freestore-mgmt.html#faq-16.12
[16.12] What if I forget the [] when deleteing array allocated via new T[n]?
All life comes to a catastrophic end.
It is the programmer's —not the compiler's— responsibility to get the connection between new T[n] and delete[] p correct. If you get it wrong, neither a compile-time nor a run-time error message will be generated by the compiler. Heap corruption is a likely result. Or worse. Your program will probably die.
这篇关于new / new []是否应与delete / delete []相匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!