views:

207

answers:

3

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();
};
+2  A: 

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.

Uri
+3  A: 

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(); 
};
Eclipse