As stated in the title, here is my code:
class Foo {
public:
Foo (int charSize) {
str = new char[charSize];
}
~Foo () {
delete[] str;
}
private:
char * str;
};
For this class what would be the difference between:
int main () {
Foo* foo = new Foo(10);
delete foo;
return 0;
}
and
int main () {
Foo* foo = new Foo(10);
foo->~Foo();
return 0;
}
The answer is yes. Destructor for each object is called. On a related note, you should try to avoid using delete whenever possible.
3. What is the difference between delete and delete[] in C++? Explanation: delete is used to delete a single object initiated using new keyword whereas delete[] is used to delete a group of objects initiated with the new operator. 4.
Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.
When an object goes out of scope normally, or a dynamically allocated object is explicitly deleted using the delete keyword, the class destructor is automatically called (if it exists) to do any necessary clean up before the object is removed from memory.
Calling a destructor releases the resources owned by the object, but it does not release the memory allocated to the object itself. The second code snippet has a memory leak.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With