我最近在工作中遇到了这个问题.我正在使用的库使用引用计数对象并实现自己的处理方式.部分实现是库的每个类都有一个私有析构函数.我猜测这是为了防止在库自动管理对象生存期时在堆栈上创建对象(它是一个场景图).
无论如何,我想在堆上分配这样一个类的数组并遇到以下问题:
#include <iostream>
using namespace std;
class test
{
public:
test() {
cout << "ctor" << endl;
}
//~test() = delete; also doesnt work
private:
~test()
{
cout << "dtor" << endl;
}
};
int main()
{
//works
auto oneInstance = new test;
//doesnt work
auto manyInstances = new test[3];
}
Run Code Online (Sandbox Code Playgroud)
数组分配使用GCC产生以下错误:
source_file.cpp: In function ‘int main()’:
source_file.cpp:15:5: error: ‘test::~test()’ is private
~test()
^
source_file.cpp:26:36: error: within this context
auto manyInstances = new test[3];
^
Run Code Online (Sandbox Code Playgroud)
为什么析构函数需要公共/可用才能在堆上分配此类的数组?当只分配像之前一行中的单个实例时,它工作正常.我也尝试使用更现代的"删除"语法,但它产生了相同的结果.
新的[]运算符中是否有任何我不知道的魔法?
编辑:
感谢您的快速帮助.我想知道为什么这段代码没有打印"dtor"两次但是: …