(Bryan) wrote in message news:<. com>...
> I've been messing around with a C++ application on Xbox, and have been
> encountering problems with my objects getting garbage collected when
> they go out of scope, but before I'm actually done using them.
There is no garbage collection in C++, unless you talk about managed
C++ in the .NET world.
> I have a function (doesn't matter if it's a class method or just a
> random function) which instantiates an object of the Rect class by
> calling its constructor ( Rect asdf = Rect(100, 200, ... ); ) and then
> returns a pointer to asdf. However, once the function returns, asdf
> gets garbage collected (at least, I'm assuming that's what happens,
> since it's the only explanation I can think of for...)
As you invoked "Rect asdf = Rect()" and not "Rect* asdfPtr = new
Rect()", your Rect instance sits on the stack, and will be lost as
soon as the function returns. The pointer returned will point to
nirvana by then. You could return asdf itself, so it will be passed
back to the caller, and the caller can then assign it to another Rect
instance (this would involve a copy constructor invocation though).
> There are probably a couple things
> about constructors in C++ I don't know that would help out here, so if
> anyone can help me out with that or suggest other ideas about how to
> fix this problem I'd appreciate it. Thanks in advance.
You must distinguish between objects on the stack (which run out of
scope) and the heap, where dynamic memory allocation happens (as by
invoking malloc resp. new), and where you are responsible for free'ing
/ deleting them as soon as they are not longer needed.
If you come from the Java world, consider that there all objects are
heap-based and garbage-collected (simple datatypes are stack-based),
which is not the case in C++.
Kind regards,
Arno Huetter