在一个函数中释放所有堆内存 [英] free all heap memory in one function
问题描述
您如何看待此代码?
what do you think about this code ?
#include <iostream>
using namespace std;
struct exam{
int id;
char name[10];
};
void deleteP(void* ptr)
{
delete []ptr;
ptr = NULL;
}
int main()
{
int *p1 = new int [10];
char *p2 = new char[10];
double *p3=new double[10];
exam *p4 =new exam();
//use variable's
deleteP(p1);
deleteP(p2);
deleteP(p3);
deleteP(p4);
return 0;
}
推荐答案
void deleteP(void* ptr)
{
delete []ptr;
ptr = NULL;
}
您确实意识到这只会将临时指针标记为NULL
;;.原始文件仍指向已释放的块.另外,对deleteP(p4)
的调用是错误的,因为p4
不是数组.
You do realise that this will only mark the temporary pointer as NULL
,; the original still points to a deallocated block. Also the call to deleteP(p4)
is wrong as p4
is not an array.
不,这是一个垃圾概念,即使它是有效的C ++并且按照您的想法做了做过.首先,在您的示例中,不需要动态分配的数组.其次,如果要动态数组,请使用vector
.如果由于某种原因不能使用vector
,请使用std::shared_ptr
或std::unique_ptr
.
因此,使用ptr对象:
No, it''s a rubbish idea, even if it was valid C++ and did what you thought it did. First off in you example there was no need for a dynamically allocated array. Second if you want dynamic arrays then use avector
. If you can''t use avector
(for some reason) use astd::shared_ptr
orstd::unique_ptr
.
So using ptr objects:
#include <memory>
struct exam{
int id;
char name[10];
};
int main()
{
std::unique_ptr<int> p1( new int [10] );
std::unique_ptr<char> p2( new char[10] );
std::unique_ptr<double> p3( new double[10] );
std::unique_ptr<exam> p4( new exam() );
//use variable's
// Er, that's it
}
看不到删除,不需要调用函数的负载来释放内存.
或最好使用std::vector
:
Not a delete in sight, no need to call loads of functions to free memory.
Or preferably using std::vector
:
#include <vector>
struct exam{
int id;
char name[10];
};
int main()
{
std::vector<int>< p1( 10 );
std::vector<char> p2( 10 );
std::vector<double> p3( 10 );
std::unique_ptr<exam> p4( new exam() );
//use variable's
// er, that's it again
}
或更优选地使用自动对象:
Or even more preferably using automatic objects:
struct exam{
int id;
char name[10];
};
int main()
{
int p1[10];
char p2[10];
double p3[10];
exam p4;
//use variable's
// yet again nothing else to do
}
基本上,第一个规则是不要直接摆弄内存.有时您必须这样做,但除非其他C ++机制之一可以胜任.第二条规则是,如果必须使用堆,则将new的返回值分配给ptr对象,以便自动调用析构函数.
Basically the first rule is don''t fiddle with memory directly. Sometimes you have to but unless one of the other C++ mechanisms will fo the job. The second rule is that if you do have to use the heap then assign the returned value from new to a ptr object so the destructor gets called automagically.
这篇关于在一个函数中释放所有堆内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!