Assignment to a pointer immediately after deletion

I was wondering if this is safe to do ...

delete p_pointer;
p_pointer = p_otherPointer;

Instead of...

delete p_pointer;
p_pointer = 0;
p_pointer = p_otherPointer;

I would suggest so, as there are no new memory allocations between deletion and assignment, but I just want to make sure.

+3
source share
3 answers

Yes, it is safe. It is incorrect to set the remote pointer to NULL if you intend to reassign it anyway. The reason people set remote pointers to NULL is because they can β€œmark” it as deleted, so they can check later if they have deleted it yet.

+16
source

. delete - . , . .

, , -, , .

+6

Actually auto_ptr::resetdoes just that (at least in the implementations I've seen)

+1
source

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


All Articles