Sunday, March 27, 2011

Controlling object creation

I have a class whose object must be created on the heap. Is there any better way of doing this other than this:

class A
{
public:
  static A* createInstance(); //Allocate using new and return
  static void deleteInstance(A*); //Free the memory using delete

private:
  //Constructor and destructor are private so that the object can not be created on stack
  A(); 
  ~A();
};
From stackoverflow
  • This is pretty much the standard pattern for making the object heap-only.

    Can't really be simplified much, except that you could just make the destructor private without forcing the use of a factory method for creation.

  • I'd suggest making only the constructor private and return a shared_ptr to the object instead.

    class A
    {
    public:
      static sharedPtr<A> createInstance(); //Allocate using new and return
    
    private:
      //Constructor is private so that the object can not be created on stack
      A(); 
    };
    
  • Check this at C++ FAQ lite:

    [16.21] How can I force objects of my class to always be created via new rather than as locals or global/static objects?

0 comments:

Post a Comment