我怎么知道一个指针是否已经通过'new'分配了数据?

编程入门 行业动态 更新时间:2024-10-27 22:31:40
本文介绍了我怎么知道一个指针是否已经通过'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,

也有效.只要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'分配了数据?

本文发布于:2023-08-02 13:30:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1278199.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   配了   我怎么   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!