On Fri, 2006-10-20 at 19:49 +1000, Erik de Castro Lopo wrote: > Here's a question for all the C++ crack monkeys. Is it possible > to return an std::string from a function? > > Something like: > > std::string & > return_string () > { > std::string s ; > > // Do something with s. > > return s ; > }
Of course... just leave off the "reference to" unless you are returning a reference to a static, or something that has scope which persists beyond the function execution. There is quite a lot on this subject in C++ books, particularly ones which talk about implementation issues. Class instance return values are frequently implemented as a copy constructor (modulo the availability of various constructors and the assignment operator), and there is an implicit argument which is a pointer to the uninitialised variable to hold the return value of the function. On stack machines it could be an uninitialised hunk of stack other side of the pushed return address. There are other implementations, too, but no specific one is mandated by the standard. And if all else fails, the things that make it possible to return a struct from a C function, make it possible to return a struct from a C++ function (remembering struct and class are identical in C++, access protection aside). Wherever C would do a bit-wise copy, C++ will use an implicit or explicit constructor... and the fallback is a bit-wise copy. And then there are optimisations: your example begs for the optimiser to notice that it is possible for s to be the place the return value will be copied to anyway, and not within the function's stack frame at all. _______________________________________________ coders mailing list coders@slug.org.au http://lists.slug.org.au/listinfo/coders