How to implement the factory method pattern in C++ correctly

后端 未结 11 1076
暗喜
暗喜 2020-11-22 14:55

There\'s this one thing in C++ which has been making me feel uncomfortable for quite a long time, because I honestly don\'t know how to do it, even though it sounds simple:<

11条回答
  •  情歌与酒
    2020-11-22 15:14

    I mostly agree with the accepted answer, but there is a C++11 option that has not been covered in existing answers:

    • Return factory method results by value, and
    • Provide a cheap move constructor.

    Example:

    struct sandwich {
      // Factory methods.
      static sandwich ham();
      static sandwich spam();
      // Move constructor.
      sandwich(sandwich &&);
      // etc.
    };
    

    Then you can construct objects on the stack:

    sandwich mine{sandwich::ham()};
    

    As subobjects of other things:

    auto lunch = std::make_pair(sandwich::spam(), apple{});
    

    Or dynamically allocated:

    auto ptr = std::make_shared(sandwich::ham());
    

    When might I use this?

    If, on a public constructor, it is not possible to give meaningful initialisers for all class members without some preliminary calculation, then I might convert that constructor to a static method. The static method performs the preliminary calculations, then returns a value result via a private constructor which just does a member-wise initialisation.

    I say 'might' because it depends on which approach gives the clearest code without being unnecessarily inefficient.

提交回复
热议问题