user4634931
user4634931

Reputation:

C++ delete object as reference

I have always allocated and cleaned up memory in C++ the proper way.

SomeObject *Object = new SomeObject();

delete Object;

However, recently I discovered that this compiles and executes.

SomeObject *Object = new SomeObject();

delete &Object;

So what is happening in memory here? is it cleaning up properly or is it only deleting the reference to the object, leaving it in abandoned in memory?

Upvotes: 0

Views: 2597

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409136

First of all the meaning of the & operator depends on context. In the context you use it, it has nothing to do with references but is the address-of operator.

Somewhat semi-graphical the pointers and the data you allocate looks something like this:

+---------+     +--------+     +------------------------------+
| &Object | --> | Object | --> | Instance of SomeObject class |
+---------+     +--------+     +------------------------------+

That is, &Object points to the location where the variable Object is located, and Object points to where the instance for the SomeObject class is located.

When you do delete &Object you are telling the system to free the memory allocated for the variable Object, but that memory you did not allocate yourself (you allocate the memory where Object points). Passing an invalid pointer to delete leads to undefined behavior.

Upvotes: 4

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385088

It's just wrong, plain and simple.

You didn't dynamically allocate Object (you only dynamically allocated the thing it points to), so by passing its address to delete, you give your program undefined behaviour.

Here's a roughly equivalent example:

int  x   = 42;
int* ptr = &x;

delete ptr;   // yikes!

Any unlikely thing could happen, including appearing to work or making me a more pleasant person.

Upvotes: 4

Related Questions