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
class String
{
public:
String();
String(constchar* rhs);
String(const String& rhs);
String& operator=(const String& rhs);
private:
char* mData;
};
String::String(constchar* 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 = newchar[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.
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.
//need int *
int *Ptr = newint;
//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;
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.