回答
的基本思想是計算在一些靜態變量,創建實例的數量。我會像這樣執行它。存在更簡單的方法,但是這種方法有一些優點。
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> {
}
只要你定義了一個模板超類,你也可以爲最大數量的實例添加第二個模板參數。 I.e .:'template
+1。但最好將靜態成員封裝到內聯存取器函數中,以避免源文件中的模板定義。 – Potatoswatter
@Potatoswatter,thx,編輯 – unkulunkulu
您正在查找實例管理器模式。基本上你所做的就是將那個類的實例化限制在一個經理類中。
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. 我如何限制實例化對象的數量?
- 2. 從結構/類實例化的對象的變量數
- 3. 如何限制EJB實例的數量?
- 4. Symfony命令實例的限制數量
- 5. 如何將一個類的對象的數量限制爲ruby中給定的數字?
- 6. 通過給定的字段對象查找類實例
- 7. 實例變量和對象,定義類
- 8. 將實例方法的參數限制爲實例的類型
- 9. 限制加載對象的數量
- 10. Mongoid:限制嵌入對象的數量
- 11. has_many association中的對象數量限制
- 12. 限制不使用靜態變量創建類的實例數
- 13. 如何限制C++或JAVA中類的實例數量?
- 14. 如何限制從特定功能創建的實例的數量
- 15. 休眠條件限制由屬於限制類的實例對象
- 16. 對象的構造函數 - 獲取實例變量的名字
- 17. 確實NDISUIO對以太類型的數量限制監聽
- 18. 如何限制float輸入中給定的數字量? (Python)
- 19. 訪問給定子對象的對象的父(或實例?)
- 20. 根據表中實例的數量限制數據輸入
- 21. JSON到定製的PHP對象實例
- 22. 確定JavaScript對象實例的類型
- 23. 將值分配給Java類實例對象中的字段
- 24. java強制基於實例變量的方法參數對象類型
- 25. 檢查Swift對象是否爲給定元類型的實例
- 26. 限制刪除全部到一定數量的對象
- 27. MATLAB:函數來顯示類實例的名字(對象)
- 28. NodeJS對象實例 - 類或函數
- 29. 無法從ruby中的類實例獲取對象數據
- 30. 實例化對象的類
這取決於。實例副本是否算作新實例?還是很好? –
你說對象_creations_而不是_instances_。如果我創建4個實例,然後刪除一個,我應該允許創建另一個嗎?你也可以考慮線程安全。值得注意的是,下面的答案都沒有考慮到這一點(雖然它不是一個特別複雜的擴展) – Rook