2009-01-30 56 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(); 
}; 
相關問題