C ++ reassign pointer and then delete it

Is it safe and correct? I mean, is the deletion deleted only at the address specified by it, or is it important to delete the original pointer variable?

myClass *p1 = new myClass(); myClass *p2 = p1; delete p2; p1 = NULL; p2 = NULL; 
+4
source share
4 answers

Delete only cares about the address, so your code is completely legal.

+6
source

Is it safe and correct?

It works. That is, it has a well-defined behavior and does not leak (provided that it compiles).

But is it safe? It is a dangerous idea to have smooth pointers run freely. You must keep track of which pointers have been deleted and which have not; which indicate the memory to be deleted, and which are not.

It is much safer to use RAII-enabled handles to control your dynamically allocated objects, such as std::unique_ptr and std::shared_ptr (or force replacements). std::unique_ptr does not allow aliasing, and std::shared_ptr allows you to use aliases safely.

+6
source

Since p1 and p2 point to the same object, if you delete through p2, you will also delete what p1 pointed to. So this is correct.

+3
source

This is normal. You allocated memory to p1, then pointed SAME memory to p2. When you called delete on p2, the memory in which p1 was also deleted was also deleted (this is one and the same, location and all). It is also fixed that you set both of them to NULL, since deleting p1 otherwise after that could cause some problems, since it no longer indicated the actual memory.

+1
source

Source: https://habr.com/ru/post/1393231/


All Articles