Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to delete an object created by factory?

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 a new DestructObject function which I should have together with the factory?

like image 506
Igor Avatar asked Jul 11 '10 07:07

Igor


3 Answers

In the general case, the factory might not use plain old new to allocate the object. It may use object and/or page pooling, malloc with placement new, or something even more exotic (memory mapping?). There are at least three ways to handle this that I can think of:

  1. Have the factory supply a recycle method to be called when you are done with the object.
  2. Return a smart pointer that knows how to do away with the object once no referers remain.
  3. Implement a custom delete operator in the object itself.

I hesitate to recommend one over the other, since I haven't given it enough thought in the last five minutes to proffer a definitive opinion, but I would tend to favour the last option in combination with a regular smart pointer like boost/tr1::shared_ptr.

like image 148
Marcelo Cantos Avatar answered Nov 19 '22 20:11

Marcelo Cantos


The best way to delete it manually would be not at all.

like image 1
BlueRaja - Danny Pflughoeft Avatar answered Nov 19 '22 22:11

BlueRaja - Danny Pflughoeft


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

class FooFactory
{
public:
    static std::auto_ptr<Foo> CreateInstance();
};

// transmit ownership of created object from factory to 'a' variable
std::auto_ptr<Foo> a = FooFactory::CreateInstance();
// using the created object is not required
FooFactory::CreateInstance();
like image 1
Sergey Avatar answered Nov 19 '22 22:11

Sergey