Gre*_*lin 4 c++ memory heap operating-system pointers
今天,在文章堆损坏的 EFNet C++ Wiki上,我找到了两段代码.
void this_is_bad() /* You wouldn't believe how often this kind of code can be found */
{
char *p = new char[5]; /* spend some cycles in the memory manager */
/* do some stuff with p */
delete[] p; /* spend some more cycles, and create an opportunity for a leak */
}
Run Code Online (Sandbox Code Playgroud)
替代方式:
void this_is_good()
{
/* Avoid allocation of small temporary objects on the heap*/
char p[5]; /* Use the stack instead */
/* do some stuff */
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮助我理解为什么第一段代码不被认为是好的吗?
在使用时char* p
,您在p
堆上进行分配,因此您必须在最后处理它.之间的char *p
和delete
,在do some stuff with p
中,代码可能抛出一个异常,p
被泄露.
在使用时char p[5]
,你在p
堆栈上分配你不需要处理的方式delete
,即使代码抛出异常,你也是安全的.
void this_is_bad()
{
char *p = new char[5]; //on the heap
// What happens if I throw an unhandled exception here?
delete[] p; // I never get to delete p and it gets leaked
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1582 次 |
最近记录: |