Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

c++ - after delete pointer, the occupied space for the str pointer self can exist?

string *str=new string;
delete str;

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...