The third example will not work because the T2COLE
object created in the method will be destroyed as soon as you return from the function. As you note in your question, the object is created on the stack, and the usual stack rules apply in this situation - the object will be destroyed as soon as you go out of scope, and you'll be accessing garbage data in the 3rd case.
The second case is the correct mechanism to use for using the data without triggering a stack overflow as upon return from the function, the memory that was allocated by the T2COLE
will be freed.
I'm not aware of how the implementation of T2COLE
works, but in C, you could achieve the same behaviour by using the alloca
function which suffers from the same issue - as soon as you return from the function, you should consider the pointer and the data that it points at as invalid.