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:
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.
well my taste go to returning a smart pointer. here is a link to an example Abstract factory that returns a smart pointer.
my2c
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With