gpt4 book ai didi

c++ - 如何在 C++ 中释放指向结构的指针数组?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:51:09 25 4
gpt4 key购买 nike

我创建了实现结构指针数组的类...我知道如何将记录添加到这个数组,但我不知道如何正确删除它们,因此我遇到了内存泄漏。我的数组的大小会在需要时增加,我知道数组的大小以及那里有多少条记录。我习惯用有垃圾收集器的语言编写代码,所以这让我很困惑。如果你们中的任何人能告诉我如何正确地释放该数组,我将很高兴。

请注意,我不能使用vector。我仅限于包括那些:

#include <iostream>
#include <iomanip>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cstdio>

我的代码:

struct DbRecord
{
string oName;
string oAddr;
string cName;
string cAddr;
};

class CCompanyIndex
{
public: CCompanyIndex(void);~CCompanyIndex(void);
bool Add(const string & oName,
const string & oAddr,
const string & cName,
const string & cAddr);
bool Del(const string & oName,
const string & oAddr);
bool Search(const string & oName,
const string & oAddr,
string & cName,
string & cAddr) const;

int size;
int position;
DbRecord * * db;
};

CCompanyIndex::CCompanyIndex(void)
{
db = new DbRecord * [1000];

size = 1000;
position = 0;
}

CCompanyIndex::~CCompanyIndex(void)
{
}

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

CCompanyIndex c1;
// do something..with c1, i.e. add there some records to array
// ...
// ...
// delete it now
}

最佳答案

经验法则是在析构函数中反转在构造函数中完成的与内存管理相关的操作。也就是说,既然你在构造函数中有 db = new DbRecord * [1000];,你应该在析构函数中有一个 delete[] db;

请注意,您很可能在这里不需要动态内存管理(使用按值语义),并且您可能希望研究 C++ 提供的更高级别的抽象,例如 vector 类- 正如 AndyProwl 和 JamesKanze 所建议的那样。

关于c++ - 如何在 C++ 中释放指向结构的指针数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15729787/

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