>> Or must I always use the new operator to invoke the
>> ctor to create a bonafied object?
>
> You must always use 'new' to allocate objects.
Thanks.
> Returning objects from the stack is nasty anyway. You risk overwriting them in the next function call.
Oh. In what sort of programming languages is that a problem?
In Java, when you return an int from a function, isn't that
on the stack? I don't know much about how Java is implemented,
if there is a stack but it seems, at least with primitive types,
that the conventions of passing them to, and returning them
from functions are very similar to C. For example, I don't
have to use the new operator to return an int; presumably
on the stack?

Signature
To reply by email replace dots with hyphens
Robert Larsen - 28 Jul 2009 09:43 GMT
>> Returning objects from the stack is nasty anyway. You risk overwriting
>> them in the next function call.
>
> Oh. In what sort of programming languages is that a problem?
Well, C/C++ for instance, unless you return a copy (which is just a waste).
The optimal way to "return" a large object from a function in C/C++ is to pass a reference to it from the caller:
struct SomeLargeStruct bad_way() {
struct SomeLargeStruct str;
/* ..... */
return str;/* This will
}
void good_way(struct SomeLargeStruct * str) {
/* ... */
}
In the first function the compiler will probably return a pointer to the struct, but the caller will then have to copy the struct into its own stack frame. The second function operates directly on the memory, that contains the callers version of the struct...which could even be dynamically allocated.
> In Java, when you return an int from a function, isn't that
> on the stack? I don't know much about how Java is implemented,
[quoted text clipped - 3 lines]
> have to use the new operator to return an int; presumably
> on the stack?
For simple datatypes, a copy is returned. Well, also for arrays and objects, but it is a copy of the reference.