Haquejiel wrote:
Hello. I have a question that is simultaneously simple and
complicated.
I have a custom class I wrote, and I want to return new instances of
it by reference (for odd reasons). I have the deconstructor of this
class outputting to stdout when it is called.
In MSVC++, returning a reference to a new instance of this object
seems to be legitimate - if I assign it to a local reference,
In the code below, you are not assigning to local references. You initialize
local object from the returned reference. If you want to hold references to
the allocated object, you should do:
Object & outer = someFunction();
Object & inner = someFunction();
it gets
deconstructed when it goes out of scope - but does it get deleted?
The objects allocated in someFunction are never deleted in your code. That
is a memory leak. (Note that "delete" does not appear anywhere in the
code.)
Here's an example of what I've been testing against:
Object& someFunction()
{
Object *newObject = new Object();
return *(newObject);
}
int main()
{
Object outer = someFunction();
cout << "Before" << endl;
{
Object inner = someFunction();
}
cout << "After" << endl;
return 0;
}
The result of this appears to be as such (pretending the deconstructor
outputs the object name):
Before
inner deconstructed.
After
outer deconstructed.
If I do not assign someFunction() to a value, a deconstructor is never
apparently called. Is this a memory leak?
The deconstructor is being called for inner, but is the memory getting
cleaned up?
The destructor is called for the object "inner", which is not the same
object as allocated by the someFunction() call.
[snip]
Best
Kai-Uwe Bux
Alright. Thank you very much for the prompt response. That answers my
questions. Sorry for the semantic issue on the local reference bit (I
did not meant a C++ reference - some ambiguity there).
deconstruction was throwing me off a bit.