Why does no one ever write "delete & someObj"?

Well, that may sound ridiculous, but I see code so often where dynamically allocated memory deleted using a link looks like this:

Obj* ptr = &someObj; delete ptr; 

instead of what seems like a logical alternative:

 delete &someObj; 

Is there any special reason for security, or is it just a style?

+7
c ++
source share
3 answers

No extra security. It was the style of choosing the person who wrote the cited code.

PS. It (or should be) extremely rarely to delete dynamically allocated memory through the link. This is a very common convention for storing addresses of dynamic objects in pointers. These days, it would be rare to delete any memory manually at all, since the task is conditionally delegated to smart pointers.

+3
source share

Well, if you allocate memory dynamically, then you get a pointer, not the value itself.

 int* a = new int; 

Then you need to call delete and pass the pointer:

 delete a; 

If you try to assign a variable of type int b = *a; , then b will not be dynamically allocated. So you cannot write delete &b; , because b is allocated on the stack and will be automatically cleared when it goes out of bounds. If you assign it to a link similar to int& c = *a; , then you can write delete &c; but this is a bad error prone method because you have no guarantee that the memory referenced by c will be dynamically allocated.

+2
source share

The delete operator frees a block of memory, syntax:

  • delete cast-expression
  • delete[] cast-expression

According to C ++, the cast-expression argument must be a pointer to the block of memory previously allocated to the object. Thus, delete ptr not a bit of a style, and it has nothing to do with security.

-one
source share

All Articles