Where to delete an object created by factory?

后端 未结 4 933
萌比男神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:19

    The most versatile solution for this problem is to derive your class from a base class that has a virtual "killing" function. Something like this:

    class IDisposable {
    public:
        virtual void Release() = 0;
    };
    

    It's generally believed that polymorphic objects should have virtual destructors to support proper object cleanup. However this is incomplete, because it doesn't account for potentially different memory management of objects.

    On the other hand this method doesn't require to use virtual destructors. It's now replaced by Release function that does both: invokation of the correct destructor and releasing the memory by the appropriate means.

    takes care of the object destr

    both: destruct

    The object returned from the factory will implement this "interface".

提交回复
热议问题