gpt4 book ai didi

c++ - 我应该删除 C++ 中的静态对象吗?

转载 作者:太空宇宙 更新时间:2023-11-04 14:49:14 24 4
gpt4 key购买 nike

在我的 main 函数之前,我声明了一个静态指针数组,其中包含指向实现基本数组类的对象的新指针,我想知道我是否应该使用“删除”自行删除它(或仅删除类)。

static AStudentList* a = new AStudentList();
static BStudentList* b = new BStudentList();
static CStudentList* c = new CStudentList();
static DStudentList* d = new DStudentList();
static InstitutionStudentList* instArr[4] = {a, b, c, d};

int main(int argc, char *argv[])
{
}

最佳答案

您需要在程序结束前删除这四个对象中的每一个,如下所示:

delete instArr[0];
delete instArr[1];
delete instArr[2];
delete instArr[3];

您不应该删除数组,因为它不是动态分配的。

但是,我认为没有理由在这里使用动态分配的对象。为什么不这样做:

static AStudentList a;
static BStudentList b;
static CStudentList c;
static DStudentList d;
static InstitutionStudentList* instArr[4] = {&a, &b, &c, &d};

那么你就没有什么可以删除了。

关于c++ - 我应该删除 C++ 中的静态对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20814703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com