Quote:
Originally Posted by SaswatPadhi View Post
I think we can explicitly delete the objects by calling destructors.
No, because of the marked line, which shows that EVEN THOUGH the destructor has been called, the compiler thinks it still has to call it.

Calling the destructor is one of those things you should only do if you REALLY KNOW what you are doing (and therefore don't need to ask). If you need to call the destructor, better to make the destructor call some function f() and call f() instead of the destructor.

Anyway, if you want to delete the object, why would you want to call the destructor instead of using the perfectly good "delete object;"?

Proof of concept code. If calling the destructor deletes an object then this should be an infinite loop:
Code:
class foo
{
	char x[10];
public:
	~foo() { };
};

int main(int argc, char* argv[])
{
	for (;;)
	{
		foo *bar=new foo;
		bar->~foo();
	}
	return 0;
}
On my computer this crashes after the process size increases dramatically and fills all available memory (it was char x[1000] but it crashed before I could get to Task Manager and watch the memory grow).

Changed bar->~foo(); to delete bar; and the process remained tiny and took up 100% CPU instead of 100% RAM.


*** Therefore calling a destructor DOES NOT free the object. ***


POC2: accessing object memory after deleting the object:
Code:
class foo
{
public:
	char dummy1[100];
	char x[10];
	char dummy2[100];

	foo(char *str="Hello") { strcpy(x,str); }
	~foo() { };
};

void test1()
{
	for (;;)
	{
		foo *bar=new foo;
		delete bar;
		// bar->~foo();
	}
}

void test2()
{
	foo *bar=new foo;
	delete bar;
	printf("bar->x='%s'\n",bar->x);
}

int main(int argc, char* argv[])
{
	test2();
	return 0;
}
dummy1 and dummy2 were necessary to make this work (using Visual Studio 2008).
The code prints "bar->x='Hello'".
But this is undefined behaviour, because bar has been freed.
Without the dummies, building in Release mode I got
bar->x=''
and in Debug mode I got
bar->x=''
Interestingly, with dummies and building in Debug mode I got
bar->x='
'

But anyway, this is UB because of the delete. So this code is just to prove that you will get unpredictable results if you do stupid things.

Moving the delete after the printf I got the same result in all four configurations (with and without the dummies, and in both Debug and Release mode):
bar->x='Hello'