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;
Reputation Points: 1446
Solved Threads: 135
Practically a Master Poster
Offline 681 posts
since Jun 2009