仅在堆中创建 C++ 对象

create C++ object only in heap

class A
{
public:
    A() { printf("constructor"); };
private:
    ~A() {};

};
int main(int argc, char** argv[])
{
    void *p = new A(); //ok
    void *p = new A[5]; //error
    return 0;
}

我只想在堆中创建对象(也就是说只能通过new),所以我将默认析构函数设置为private。但是,当我使用new A()只创建一个对象时它起作用,当我使用new A[5]时它不起作用。为什么?我很迷惑。非常感谢!

执行new A[5]的步骤是:

  1. 分配所需的内存量。
  2. 使用默认构造函数初始化每个对象。
  3. Return 指向已分配内存的指针。

如果上面第二步抛出异常,需要实现:

  1. 对所有已初始化的对象调用析构函数。
  2. 释放内存。
  3. 处理异常。

因此,new [] 实现需要能够访问 class 的析构函数。

试试这个解决方法。它不仅在堆上分配对象,还分配数组:

[编辑] 感谢@M.M 的建议,我可以写出更好的方法来做到这一点:NOT使用通用指针并为每个分配声明适当的指针类型,那么代码将更加简化:

#include <cstdio>

class A
{
public:
    A() { printf("constructor"); };
private:
    ~A() {};
};

int main(int argc, char *argv[])
{
    A *p1 = new A(); // ok. not using generic pointer
    A **p2 = new A*[5]; // no error anymore, also there's not a generic pointer involved
    for (int i = 0; i < 5; ++i) {
        p2[i] = new A();
    }
    return 0;
}