我怎么知道一个指针是否已经通过'new'分配了数据? [英] How do I know if a pointer has been assigned data via 'new'?

查看:293
本文介绍了我怎么知道一个指针是否已经通过'new'分配了数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个这样的指针:

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,

也有效.只要thingyNULL 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'分配了数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆