【问题标题】:Restrict the number of object instantiations from a class to a given number将类中的对象实例化数量限制为给定数量
【发布时间】:2012-06-24 15:35:47
【问题描述】:

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

有没有办法做到这一点?

【问题讨论】:

  • 这取决于。实例的副本算作新实例还是可以?
  • 你说的是对象creations而不是instances。如果我创建 4 个实例,然后删除一个,是否应该允许我创建另一个?您可能还想考虑线程安全。值得注意的是,下面的答案都没有考虑到这一点(尽管它不是一个特别复杂的扩展。

标签: c++ object instantiation


【解决方案1】:

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

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

【讨论】:

  • 只要定义模板超类,还不如为最大实例数添加第二个模板参数。即:template&lt;class T, int MAX_INSTANCES&gt; class Counter {...};
  • +1。但最好将静态成员包装到内联访问器函数中,以避免源文件中的模板定义。
  • @EdwardLoper,这是对 Luchian Grigore 回答的一种恭维,他保留了问题中的常量,发现它很有趣,将编辑,谢谢
【解决方案2】:

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

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

【讨论】:

  • 构造函数解决方案有什么难点,除了它像其他解决方案一样非常不安全的线程?
  • @rubenvb 很难搞定 :) - stackoverflow.com/questions/810839/…
  • 好的,在链接的问题中没有看到太大的相关性。需要解释一下吗?
  • @rubenvb 没什么好解释的。 :) 我只是觉得这很重要。如果这对你来说很容易,荣誉。 :)
  • 如果将计数器封装到 CRTP 基类中,从构造函数中正确抛出异常会更容易。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-08
  • 2015-02-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多