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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With