Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the preferred way to implement a factory method in C++?

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:

  1. Return a raw pointer from the factory method and wrap it into a smart pointer in the calling method
  2. Return a smart pointer from the factory
  3. 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
  4. 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.

like image 978
Grzenio Avatar asked Jan 24 '11 17:01

Grzenio


2 Answers

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.

like image 82
Konrad Rudolph Avatar answered Oct 21 '22 01:10

Konrad Rudolph


well my taste go to returning a smart pointer. here is a link to an example Abstract factory that returns a smart pointer.

my2c

like image 31
neuro Avatar answered Oct 21 '22 01:10

neuro