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

后端 未结 11 1074
暗喜
暗喜 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:24

    Simple Factory Example:

    // Factory returns object and ownership
    // Caller responsible for deletion.
    #include 
    class FactoryReleaseOwnership{
      public:
        std::unique_ptr createFooInSomeWay(){
          return std::unique_ptr(new Foo(some, args));
        }
    };
    
    // Factory retains object ownership
    // Thus returning a reference.
    #include 
    class FactoryRetainOwnership{
      boost::ptr_vector  myFoo;
      public:
        Foo& createFooInSomeWay(){
          // Must take care that factory last longer than all references.
          // Could make myFoo static so it last as long as the application.
          myFoo.push_back(new Foo(some, args));
          return myFoo.back();
        }
    };
    

提交回复
热议问题