gpt4 book ai didi

c++ - 处理 C++/C 结构内存释放

转载 作者:太空狗 更新时间:2023-10-29 23:30:58 32 4
gpt4 key购买 nike

使用后必须释放结构内存吗?我有示例代码:

struct aa 
{
int a;
char * b ;
aa()
{
a=0;
b= new char[255];
}
} ;


aa *ss = new aa[3];

void fill()
{
aa * ssss = new aa;
aa * sss = new aa;

sss->a=10;
ss[0] = *sss;
cout<<ss[0].a<<"\n";
ss[1] = *sss;

cout<<ss[1].a<<"\n";
cout<<ssss[1].a<<"\n";
}

int _tmain(int argc, _TCHAR* argv[])
{


fill();
delete(ss);
}

我必须在 fill 的末尾执行 delete(ssss) 吗?

我必须删除 main 末尾的 ss 结构数组吗?

我必须创建 destruct 还是构造 ss 来释放 *b 内存?

类呢,逻辑一样吗?

最佳答案

Must I do delete(ssss) at the end of fill?

是的,您必须删除使用 new 创建的所有内容。但是,这里不需要使用new,让它自动即可:

void fill() {
aa ssss; // automatically destroyed on exit from the function
}

Must I delete ss array of structure at the end of main?

是的,但它是一个数组,所以必须作为一个数组删除:

delete [] ss;
^^

但同样,没有理由动态分配它:

aa ss[3]; // automatically destroyed on exit from the program

Must I create destruct or to structure ss that frees *b memory?

如果你真的想使用原始指针来管理动态数组,那么是的。您还需要考虑复制构造函数和复制赋值运算符(根据 Rule of Three )以使类可以安全使用。或者,使用智能指针或容器为您管理内存:

struct aa 
{
int a;
std::vector<char> b ;

aa() : a(0), b(255) {}
} ;

What about classes is it the same logic?

是的,规则总是一样的:任何用 new 创建的东西都必须用 delete 销毁。如果尽可能避免动态分配并使用智能指针、容器和其他 RAII,管理对象会容易得多真正需要的时候上课。

关于c++ - 处理 C++/C 结构内存释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11593105/

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