I'm just re-freshing my old C++ knowledge having been emersed almost exclusively in Java/J2EE for the past 5 years. So I picked up a second hand copy of the old C++ bible 'Effective C++' by Scott Meyers and item 31 got me thinking.
I totally agree with what Mr Meyer's is saying - a local object is going to be invalid by the time the reference is returned and a new object is likely to lead to memory leaks. However unlike most of the other items in the book, an appropriate solution is not really offered.
In Java this is not an issue because the garbage collector takes care of things. However the only option I see in C++ is to create a new object before calling the other object's member function. The new object would be passed into the function which would then set the appropriate state on the new object before returning.
This seems to break the rules of encapsulation to me because the calling object seems to require too much knowledge about what the called function is going to need to create/set. Does anyone see a more straight-forward solution? In Java, the called method's return type would ideally be an interface (abstract class) not a class (concrete class) thus defering the choice of the new object's real type to the internels of the method which is being called.
How will I be able to implement the GoF 'abstract factory' and 'factory method' design patterns if the member function I call can't create the object for me? Or am I missing something obvious?
By the way - I've just discovered this discussion forum - if there's a more appropriate forum out there, which I should use, please point me at the appropriate url. :)