Its Me
Its Me

Reputation: 156

Reference Reassignment

I have a general C++ question.

Lets say I have this code:

int& GetInt()
{
    int* num = new int();
    return *num;
}

int numCopy = GetInt();

In this situation, what happens to the returned reference? This example uses a simple data structure so it doesn't really matter, but in cases where the returned data is more complex, would assigning a variable to a heap-allocated variable reference like this copy the data over to numCopy completely, or would numCopy become another reference to the original num?

Upvotes: 2

Views: 78

Answers (1)

NathanOliver
NathanOliver

Reputation: 180595

In this situation, what happens to the returned reference?

It goes out of scope at the end of the full expression and you have now leaked the memory you acquired in GetInt. You've made a copy of the value the reference refers to, but the original object, and the memory it occupies are no longer accessible.

If you had

int& foo = GetInt();

then you could later on do

delete &foo;

to not have a memory leak, but this is still bad practice.


or would numCopy become another reference to the original num?

You only ever get a reference if you specifically ask for it.

int numCopy = GetInt();

says numCopy is an int, not a int&, so it will not be a reference. C++ has what is called value semantics, which basically means unless you ask for a reference, the object you create is it's own object that is independent from all other objects.

Upvotes: 8

Related Questions