"Wang Tong" <wa******@seas.upenn.edu> wrote in message
news:bo***********@netnews.upenn.edu...
Suppose I have a function foo() and a class definition myClass, and I
want to create an instance of myClass and return it from foo(). I guess
the most efficient way is to return a reference to the object.
But here comes the problem: the object is a local one and will be
detroyed after function return. How can I return the reference from foo()?
Code:
myClass& foo()
{
myClass myObject;
...
return myObject; //Oops, myObject is a local one
}
I believe it is much better to return by value in your case.
Static myObject may fail (it depends upon the internal logic of foo) in
expressions like this:
myClass aClass = foo() + foo();
Consider the case when foo modifies myObject. If you bring yourself to make
it static then it shall be properly documented.
In case of return by value a smart compiler would change the foo call:
myClass aClass(foo());
to something like this:
char __myClass_placeholder[sizeof(myClass)];
foo(__myClass_placeholder);
myClass& aClass = *reinterpret_cast<myClass*>(__myClass_placeholder) ;
...
~aClass();
If you believe you suffer performance penalties due to foo-like code then
you might wish to consider bridge pattern.
--
Michael Kochetkov.