2012-06-24 32 views
2

鑑於一類,我想限制從這個類創建一個給定數量的對象的數量,說4從限制類對象實例的數量給定的數字

有沒有一種方法,做到這一點?

+1

這取決於。實例副本是否算作新實例?還是很好? –

+1

你說對象_creations_而不是_instances_。如果我創建4個實例,然後刪除一個,我應該允許創建另一個嗎?你也可以考慮線程安全。值得注意的是,下面的答案都沒有考慮到這一點(雖然它不是一個特別複雜的擴展) – Rook

回答

5

的基本思想是計算在一些靜態變量,創建實例的數量。我會像這樣執行它。存在更簡單的方法,但是這種方法有一些優點。

template<class T, int maxInstances> 
class Counter { 
protected: 
    Counter() { 
     if(++noInstances() > maxInstances) { 
      throw logic_error("Cannot create another instance"); 
     } 
    } 

    int& noInstances() { 
     static int noInstances = 0; 
     return noInstances; 
    } 

    /* this can be uncommented to restrict the number of instances at given moment rather than creations 
    ~Counter() { 
     --noInstances(); 
    } 
    */ 
}; 

class YourClass : Counter<YourClass, 4> { 
} 
+1

只要你定義了一個模板超類,你也可以爲最大數量的實例添加第二個模板參數。 I.e .:'template class Counter {...};' –

+1

+1。但最好將靜態成員封裝到內聯存取器函數中,以避免源文件中的模板定義。 – Potatoswatter

+0

@Potatoswatter,thx,編輯 – unkulunkulu

3

您正在查找實例管理器模式。基本上你所做的就是將那個類的實例化限制在一個經理類中。

class A 
{ 
private: //redundant 
    friend class AManager; 
    A(); 
}; 

class AManager 
{ 
    static int noInstances; //initialize to 0 
public: 
    A* createA() 
    { 
     if (noInstances < 4) 
     { 
     ++noInstances; 
     return new A; 
     } 
     return NULL; //or throw exception 
    } 
}; 

較短的方式從構造函數拋出一個異常,但可能很難得到正確的:

class A 
{ 
public: 
    A() 
    { 
     static int count = 0; 
     ++count; 
     if (count >= 4) 
     { 
      throw TooManyInstances(); 
     } 
    } 
}; 
+1

構造函數解決方案有什麼困難,除了它的可怕線程不安全,就像其他解決方案一樣? – rubenvb

+0

@rubenvb很難正確: ) - http://stackoverflow.com/questions/810839/throwing-exceptions-from-constructors –

+0

好的,在鏈接的問題中沒有看到太多的相關性。謹慎解釋? – rubenvb

相關問題