限制类的实例数

aal*_*sha 1 c++ memory c++11

我想限制你可以创建一个类的实例数.

我有以下代码:

class A {
    static int cnt;
    int x;
    public:
    A() {
        cout<<"ctor called\n";
    }
    void* operator new(size_t size_in) {
        if(cnt<=10) {
            void *p=malloc(size_in);

            if(p==NULL) {
                throw bad_alloc();
            } else {
                cout<<"Memory allocation successful\n"; 
                ++cnt;
                return p;
            }
        } else {
            throw bad_alloc();
        }
    }
    ~A() {
        cout<<"Cleaning up the mess\n";
    }
};

int A::cnt=0;
int main() {
    A *a[20];
    for(int i=0;i<20;++i) {
        try {
            a[i]=new A();
        } catch (bad_alloc &e) {
            cout<<"Error in allocating memory\n";
        }
    }
    try {
        A b;
    } catch (bad_alloc &e) {
        cout<<"Error in allocating memory on stack\n";
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

使用静态计数器并重载new操作符,我可以限制可以创建的对象数Heap.我想限制创建的实例数量Stack.一种方法是使构造函数私有并提供一个公共API,它首先检查计数器然后相应地返回.有没有其他方法这样做?

Jod*_*cus 5

有没有其他方法这样做?

您可以只在构造函数中增加并检查计数器,如果从中抛出异常,该对象将被销毁.此外,您不必区分堆栈和堆.