A newbie question: I have a hierarchy of classes with some virtual functions and I am trying to implement a factory method, but I am not sure what is the best way:
- Return a raw pointer from the factory method and wrap it into a smart pointer in the calling method
- Return a smart pointer from the factory
- Return a proper object from the factory (but is it going to copy the derived class correctly?) and assign it to a local object in the calling method
- Return a reference from the factory (but how to create the object in the factory method without a memory leak?)
I would be grateful for an example of a factory method and a minimal client, which is effective and doesn’t leak memory.
My background is C# and Java, so I am a bit lost with memory management in C++ atm.
Options 3 and 4 are out from the start because they simply don’t work: 3 slices the object, 4 creates memory leaks or invalid references.
From the other two methods, I strongly prefer 2: return a smart pointer. In fact, strive to avoid raw pointers completely, if possible. Unfortunately, C++ makes this a lot to write (and this is not a trivial objection! Anybody who has ever written object-oriented code in C++ and has used smart pointers throughout shares my pain) – but the alternative is even more pain.
Of course, there is alternative 5: use raw pointers and a garbage collector.