0

Hi All!

I have a doubt about returning reference. I'll show you an example:

Vector  &MakeVector()
	{
		Vector *result = new Vector<Dim>();
		
		/*some more code*/
		
		return *result;
	}

now I can call the function MakeVector to assign it result in this two ways:

Vector v = MakeVector(); //first case

Vector *ptrVector;  //secound case
*ptrVector = MakeVector();

I have some question about it:
in the first case: do I leave any garbage in the memory?? because I'm creating an object with the new operator, so I think that i have to free it in some place. But I know that in this case is not necessary to call the destructor because the destructor of v is called automatically. So I don't know if I'm leaving garbage in the memory.

in the secound case: I have to call the destructor in order to not leave garbage in the memory. Right ?

thanks before hand!

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by leoni
0

in the first case: do I leave any garbage in the memory??

Yes. You return a reference to a Vector, then use the copy constructor to make a copy of it in v. It causes a memory leak because you lose the reference.

in the secound case: I have to call the destructor in order to not leave garbage in the memory. Right ?

The second case will probably crash because the pointer is uninitialized, but if you initialize the pointer, you still have the same problem of needing to save the address returned by the new operator so that you can delete it and not have a memory leak.

Your design of MakeVector is the root cause of these problems. It is confusing and dangerous. If you want to allocate dynamic memory, return a pointer instead of a reference. That way it is more obvious that the memory may need to be deleted and you do not need to use tricks to get the address:

Vector* MakeVector()
{
    Vector* result = new Vector();

    /* some more code */

    return result;
}
Vector* v = MakeVector();

/* use v */

delete v;
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.