c_cpp 删除指针

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 删除指针相关的知识,希望对你有一定的参考价值。

When you have a pointer pointing to some memory there are three different things you must understand:
- there is "what is pointed" by the pointer (the memory)
- this memory address
- not all pointers need to have their memory deleted: you only need to delete memory that was dynamically allocated (used new operator).

Imagine:

int *ptr = new int; 
// ptr has the address of the memory.
// at this point, the actual memory doesn't have anything.
*ptr = 8;
// you're assigning the integer 8 into that memory.
delete ptr;
// you are only deleting the memory.
// at this point the pointer still has the same memory address (as you could
//   notice from your 2nd test) but what inside that memory is gone!
When you did

ptr = NULL;
// you didn't delete the memory
// you're only saying that this pointer is now pointing to "nowhere".
// the memory that was pointed by this pointer is now lost.
C++ allows that you try to delete a pointer that points to null but it doesn't actually do anything, just doesn't give any error.

以上是关于c_cpp 删除指针的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 指针迭代与C中的int指针

c_cpp 指针(*),地址在(@)

c_cpp C ++智能指针

c_cpp C ++指针

c_cpp const指针

c_cpp func指针练习