Why does nobody ever seem to write `delete &someObj`?

Ok, this may seem ridiculous but I so often see code where dynamically allocated memory deleted using a reference looks like this:

Obj* ptr = &someObj;
delete ptr;

instead of what seems like the logical alternative:

delete &someObj;

Is there any particular safety reason behind this, or is it just a style thing?


There is no added safety. It was a style choice of the person that wrote the quoted code.

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


Ok, if you allocate memory dynamically, then you receive a pointer, not the value itself.

int* a = new int;

Then you've got to call delete and pass the pointer:

delete a;

If you try to assign in to a variable like that int b = *a; then b is not dynamically allocated. So you can not write delete &b; because b is allocated on stack and will be automatically cleaned up when it goes out of scope. If you assign it to a reference like int& c = *a; then you are able to write delete &c; but that's a bad error-prone style, because you don't have any guarantee that the memory referenced by c is dynamically allocated.


The operator "delete" deallocates a block of memory,the syntax is:

  • delete cast-expression
  • delete[] cast-expression
  • According to C++ stipulation,the cast-expression argument must be a pointer to a block of memory previously allocated for an object. So delete ptr is not something about style,nor is it have something to do with safety.

    链接地址: http://www.djcxy.com/p/95080.html

    上一篇: LNK2001:我的boost库(可能)构建不正确

    下一篇: 为什么没有人似乎写'delete&someObj`?