说我有一个这样的指针:
Say I have a pointer like this:
int *thingy;在某些时候,此代码可能会被调用,也可能不会被调用:
At some point, this code may or may not be called:
thingy=new int;我怎么知道我是否可以这样做:
How do I know if I can do this:
delete thingy;我可以为每个指针使用bool,并在每次使用new时将布尔值标记为true,但是我有很多指针,这样会很笨拙.
I could use a bool for every pointer and mark the bool as true whenever the I use new, but I have many pointers and that would get very unwieldy.
如果我没有在thingy上调用new,则在其上调用delete可能会导致崩溃,对吧?
If I have not called new on thingy, calling delete on it would likely cause a crash, right?
我进行了很多搜索,但找不到适合自己情况的答案.
I searched around quite a bit but could find no answer that clearly fit my situation.
编辑:我需要能够多次delete多次指针,而指针不必指向任何数据.如果这不可能,那么我将不得不重新编写代码.
I need to be able to delete the pointers as many times as I like without the pointers necessarily pointing to any data. If this is impossible I'll have to re-write my code.
推荐答案始终将其初始化为NULL
Initialize it to NULL always
int *thingy = NULL;然后
delete thingy; thingy = NULL;即使thingy为NULL,
也有效.只要thingy为NULL delete,就可以进行多次删除操作.
is valid even if thingy is NULL. You can do the delete as many times as you want as long as thingy is NULL delete will have no unwanted side effects.
更多推荐
我怎么知道一个指针是否已经通过'new'分配了数据?
发布评论