Restrict the number of object instantiations from a class to a given number

百般思念 提交于 2019-12-19 04:13:02

问题


Given a class, I would like to limit the number of objects created from this class to a given number, say 4.

Is there a method to achieve this?


回答1:


The basic idea is to count the number of created instances in some static variable. I would implement it like this. Simpler approaches exist, but this one has some advantages.

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



回答2:


You're looking for the instance manager pattern. Basically what you do is restrict instantiations of that class to a manager class.

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

A shorter way is throwing an exception from the constructor, but that can be hard to get right:

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


来源:https://stackoverflow.com/questions/11178724/restrict-the-number-of-object-instantiations-from-a-class-to-a-given-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!