Must I free structure memory after using it? I have sample code:
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);
}
Must I do delete(ssss) at the end of fill?
Must I delete ss array of structure at the end of main?
Must I create destruct or to structure ss that frees *b memory?
What about classes is it the same logic?
Yes, you must delete anything created with
new. However, there’s no need to usenewhere, just make it automatic:Yes, but it is an array, so must be deleted as an array:
But again, there’s no reason for this to be dynamically allocated:
If you really want to use a raw pointer to manage the dynamic array, then yes. You will also need to think about a copy constructor and copy-assignment operator (per the Rule of Three) to make the class safe to use. Alternatively, use a smart pointer or container to manage the memory for you:
Yes, the rule is always the same: anything created with
newmust be destroyed withdelete. Managing objects is much easier if you avoid dynamic allocation where possible, and use smart pointers, containers and other RAII classes when you really do need it.