C++ 将类中的对象实例化数量限制为给定数量

C++ 将类中的对象实例化数量限制为给定数量,c++,object,instantiation,C++,Object,Instantiation,给定一个类,我想将从该类创建的对象数量限制为给定数量,比如4个 有没有实现这一点的方法?您正在寻找实例管理器模式。基本上,您要做的是将该类的实例化限制为manager类 class A { private: //redundant friend class AManager; A(); }; class AManager { static int noInstances; //initialize to 0 public: A* createA() {

给定一个类,我想将从该类创建的对象数量限制为给定数量,比如4个


有没有实现这一点的方法?

您正在寻找实例管理器模式。基本上,您要做的是将该类的实例化限制为manager类

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

其基本思想是统计某个静态变量中创建的实例数。我会像这样实现它。存在更简单的方法,但这种方法有一些优点

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> {
}
模板
班级计数器{
受保护的:
计数器(){
if(++noInstances()>maxInstances){
抛出逻辑_错误(“无法创建另一个实例”);
}
}
int&noInstances(){
静态int-noInstances=0;
返回noInstances;
}
/*可以取消注释以限制给定时刻的实例数,而不是创建实例数
~Counter(){
--noInstances();
}
*/
};
你的班级班级:柜台{
}

constructor解决方案有什么困难,除了它与其他解决方案一样具有可怕的线程不安全性之外?@rubenvb很难正确:)-好的,在链接的问题中没有看到太多的相关性。想解释吗?@rubenvb没什么要解释的。:)我只是觉得这不是小事。如果这对你来说很容易,那就太好了。:)如果将计数器封装到CRTP基类中,则从构造函数正确抛出异常会更容易。这取决于。实例的副本算作新实例吗?或者它们可以吗?你说的是对象创建,而不是实例。如果我创建4个实例,然后删除一个,是否允许我创建另一个?您可能还需要考虑线程安全性。值得注意的是,下面的答案都没有考虑这个问题(尽管它不是一个特别复杂的扩展。只要你定义了一个模板超类,你还可以为最大数量的实例添加一个第二模板参数。;+1.但是最好将静态成员包装到内联访问器函数中,以避免源文件中的模板定义。@EdwardLoper,这是对Luchian Grigore的回答的一种赞美,他在回答中保留了这个常量,觉得很有趣,将进行编辑,谢谢
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> {
}