What is the difference between deleting a pointer and setting it to nullptr?

He says delete pointer, and pointer = nullptrthe same thing? Probably not, but do the latter free up memory? What about delete pointer; pointer = nullptr/ pointer = nullptr; delete pointer? Why not use this to make a safe way to delete pointers prematurely, if necessary, where they will usually be deleted at another time and cause an error during normal deletion?

+4
source share
5 answers

This is not the same, because although you can set the pointer to zero, the contents that the pointer pointed to will still take up space.

Performance

delete pointer;
pointer = NULL;

Great but

pointer = NULL;
delete pointer;

, NULL, delete (, ). , , (, ), - .

+7

pointer = nullptr; - . , , , . .

delete pointer; . , , ( ), , . , , , .

+9

delete pointer pointer = nullptr ? , , ?

A delete (.. ). , , .

delete pointer; pointer = nullptr/pointer = nullptr; delete pointer?

, , . , , , , .

, , - , . ; , - , , , , .

, , , ?

, ...

+3

, . nullptr , , .

nullptr delete, , , delete , op, .

+1

delete , .

, .

Of course, fundamental types do not have destructors, and a call to delete will only free the memory occupied by an object of a fundamental type.

But in general, objects of user types require calling their destructors when they are deleted.

And the pointer should point to an object. Therefore, this sequence of statements makes no sense

pointer = nullptr; delete pointer;

because it is nullptrnot a valid object address. This is a NULL pointer literal.

0
source

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


All Articles