delete in destructor or main()

hi

i wonder if it is same, if u use "delete" in a destructor of a class or (at the end of) in main(), since destructor gets called when an object is destroyed, and the object gets destroyed when program quits if im not mistaken?
example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class String
{
public:
String();
String(const char* rhs);
String(const String& rhs);
String& operator=(const String& rhs);
private:
char* mData;
};


String::String(const char* rhs)
{
// Get the length of the rhs c-string.
int len = strlen(rhs);
// Allocate enough memory to store a copy of the c-string plus
// one more for null-character.
mData = new char[len+1];
// Copy characters over to our own data.
for(int i = 0; i < len; ++i)
mData[i] = rhs[i];
// Set null-character in the last spot.
mData[len] = '\0';
}

String::~String()
{
delete[] mData;
mData = 0;
}


would it be the same, if delete was writen at the end of main (/after we dont need the object anymore)?
Yes, on the machine level it's the same. But then if you removed delete [] mData; from your destructor you would have to call delete every single time you use your class. You will end up writing more achieving the same.
Last edited on
It will be the same in this specific case. But what if you wanted it to be deleted sooner? You don't want to have to do it manually.

Actually, deleting memory at the end of main would be pointless since when your program terminates all of its memory is automatically released by the OS.
how can an object be destroyed sooner then automatically when a program exits?
Last edited on
1
2
3
4
5
6
7
//need int *
int *Ptr = new int;
//do stuff
//don't need it anymore
delete Ptr; //deleted before the program exits, so I can have memory for other stuff
//do other stuff
return 0;
@Claimz:

Given the following code:

1
2
3
4
5
6
7
8
#include <string>

std::string global_string( "Global" );

int main() {
    std::string local_string( "Local" );
    std::string* pNewString = new std::string( "Heap" );
}


You will find that two destructors are called when main returns: one for local_string and one for global_string. The third object (heap) is never destroyed.

Having said that, however, the memory used by the third string will be freed when your program exits. It is a function of the operating system to ensure that all (heap) memory given to a program is freed when the program exits, otherwise this would be a tremendous security hole.

Hope this clears things up.

Topic archived. No new replies allowed.