2009-01-30 62 views
1

我有一个类,其对象必须在堆上创建。除此之外是否还有其他更好的方法:控制对象创建

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

回答

3

这几乎是制作对象堆的标准模式。

除了可以在不强制使用工厂方法创建的情况下使析构函数保持私有状态之外,不能真正简化很多。

4

我建议只将构造函数设为private并将shared_ptr返回给对象。

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