后删除指针,占用的空间为str指针自身可以存在? [英] after delete pointer, the occupied space for the str pointer self can exist?

查看:161
本文介绍了后删除指针,占用的空间为str指针自身可以存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  string * str = new string; 
delete str;删除对象后,$ str $ b

,可以占用str指针自己的空间吗?

解决方案

当然是的。类型 string * 的变量 str 仍在作用域中。它将在其当前范围退出后立即停止。例如,在函数或 {} -delimited块的末尾,包含这些说明。



优良做法是停止指向地址,其中新字符串曾经分配,现在它不再有效。对现有的指向有效内存或NULL总是好的。

  string * str = new string; 
delete str;
str = NULL;注意,在第三行之后,你现在可以问是str指向一个有效的内存位置吗?。 ,即我可以安全地解除引用吗?。

  if(str!= NULL)... 

没有将指针设置为NULL,另一方面,你不可能这样做种类的支票。你应该记住,在删除指令后,它现在是无效的反引用str,因此不做它。显然这是调用麻烦。



虽然正确,这种代码(一个新的本地匹配删除,并且任何活的指针在删除其目标内存后设置为NULL位置)相当脆弱,并且在将来更改的情况下容易出错。例如,如果函数不是那么简单,并且在新和删除之间的路径中有条件和循环?如果你传递str到另一个函数作为参数怎么办?这个函数对指针做了什么:复制它,克隆它指向的对象...?



一种叫做 RAII-资源分配初始化(请参见此问题)有助于创建防止出现内存泄漏和内存访问违规等错误的设计。



注意:稍微更直观,虽然在这个网站上建议使用较少的RAII正统名称:UDSTMR - 使用析构语义来管理资源,或UTSTTC - 触发器清除。请参见此答案


string *str=new string;
delete str;

after delete object, can the occupied space for the str pointer self exist?

解决方案

Yes, of course. The variable str, of type string *, is still in scope. It will cease to exist as soon as its current scope is exited. For example at the end of the function or { }-delimited block which contains these instructions.

This is why it is good practice to stop pointing to the adress where new string was once allocated, and which now it is no longer valid. It's always good for an existing to point to either valid memory or NULL.

string *str = new string;
delete str;
str = NULL;

Note that after the third line you can now ask "is str pointing to a valid memory location?", i.e. "can I dereference it safely?".

   if (str != NULL) ...

Without setting the pointer to NULL, on the other hand, you couldn't possibly do this kind of check. You should just remember that after the delete instruction it is now invalid to dereference str, and hence not do it. Clearly this is calling for trouble.

Although correct, this kind of code (a new locally matched with a delete, and any living pointer set to NULL after deleting its target memory location) is quite vulnerable and error prone in case of future changes. For example, what if the function isn't so simple, and in the path between new and delete you have conditionals and loops? What if you passed str to another function as a parameter? What did this function do with the pointer: copy it, clone the object it points to...?

A technique called RAII - Resource Allocation Is Initialization (see this question) helps to create designs that prevent such kinds of errors as memory leaks and memory access violations.

Note: Slightly more intuitive, although less orthodox names for RAII have been suggested on this site: UDSTMR - Using Destructor Semantics To Manage Resources, or UTSTTC - Using The Stack To Trigger Cleanup. See this answer.

这篇关于后删除指针,占用的空间为str指针自身可以存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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