在CallBack函数中删除由new创建的指针 [英] delete pointers created by new in CallBack Function
问题描述
我执行以下操作:
LRESURT CALLBACK WindowProc{
.......
Case VK_RETURN:
int i;
for ( i = 0; i <1000; i++) {
int size = determinesize(i);
int *pttest = new int[size];
.....(some work)....
delete[] pttest;
}
........
}
但是,当 VK_RETURN
发生时,我遇到问题。如果我不使用 delete [] pttest
。
But I got problem when VK_RETURN
occurs. If I don't use delete[] pttest
.
我的问题是:我需要删除ptttest ?当我在google上搜索时,几乎每个人都说,对于每一个新的,必须有一个删除。另一个问题是:如果我把 VK_RETURN
的for循环代码放在一个函数中,比如说 void whenvkreturn()
那么我需要删除pttest吗?因为任何局部变量在返回后被销毁,我猜这个循环中创建的1000个对象将被自动删除,对吗?我不知道堆栈很好,所以一些解释我发现是不清楚为我。
My question is that: Do I need to delete ptttest? When I search on google, almost everyone said that for each new, there must be a delete. Another question is that: if I put the for loop code for VK_RETURN
in a function, say void whenvkreturn()
, then do I need to delete pttest? Since any local variables are destroyed after returning, I guess the 1000 objects created in this loop will be deleted automatically, right? I don't know the stack very well, so some explanation I found is not clear for me.
=====
OK,有一个向量的解决方法。但是在这种情况下:
OK, there is a vector workaround. But when it is the case:
TCHAR * text = new text [size];
我应该做什么?
推荐答案
您总是需要删除分配的内存。对于每个新,应该有删除,即使它在一个函数中。你正在接近的问题,可以很容易地通过使用动态大小,如std :: vector的其他容器来解决。在本地函数中使用动态容器,它会自动释放自己分配的内存,你不必担心。
You always need to delete allocated memory. For every new there should be a delete, even though it is in a function. The problem you are approaching, can easily be solved by using other containers with dynamic sizes, like std::vector. Using dynamic containers in local functions, it will automatically release the memory allocated by itself, and you don't have to worry.
这篇关于在CallBack函数中删除由new创建的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!