Where to delete an object created by factory?

后端 未结 4 916
萌比男神i
萌比男神i 2021-02-19 04:01

If I have a factory, that creates an object and returns a pointer to it, what will be a better way to delete it:

By delete call in the \"user\" code, or by

4条回答
  •  感动是毒
    2021-02-19 04:26

    The following code provides an opportunity not to think about who should remove the newly created object.

    class FooFactory
    {
    public:
        static std::auto_ptr CreateInstance();
    };
    
    // transmit ownership of created object from factory to 'a' variable
    std::auto_ptr a = FooFactory::CreateInstance();
    // using the created object is not required
    FooFactory::CreateInstance();
    

提交回复
热议问题