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

前端 未结 2 1579
有刺的猬
有刺的猬 2021-01-07 06: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?

2条回答
  •  抹茶落季
    2021-01-07 06:47

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

提交回复
热议问题