Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 893
Geoff Avatar asked Feb 09 '17 10:02

Geoff


2 Answers

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.

like image 89
eerorika Avatar answered Oct 14 '22 14:10

eerorika


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.

like image 20
Alexander Lapenkov Avatar answered Oct 14 '22 13:10

Alexander Lapenkov