what does this code do??

1
2
3
4
5
6
7
8
9
10
11
12
13
14
template <class x>
void destroy(x* a)
{
	a->~x();
}

int main ()
{
	int x=5;
	destroy(&x);
	cout<<x;
	//d.foo();
	cin>>z;
}


i thought that the code destrys x(that is equal to 5)

but it doesnt..
any explanation??
When passed a pointer to a class it calls the class' destructor...which is probably bad. I can't think of a time you'd ever want to call a destructor other than when writing a memory manager.
this is to pass the exam..
but why it doesnt delete x??
The destructor is a member function that is automatically called just before a instance of that class is destroyed. This does not mean that the instance is always destroyed after the destructor, since you can (as seen above) call it manually. This merely means that you called the destructor of a instance.

If you want to "destroy" variables like that, you need to allocate them on the heap or properly scope them, store them in a STL container or do some memory management of your own.
Destructors don't destroy objects, they are just there to clean up resources once the program has decided that an object is to be destroyed
ok thank you very much i understand now!
The destructor for int does not modify the memory locations that the int occupied.
Therefore, as long as the stack space occupied by x is not overwritten between
lines 10 and 11 (which it isn't), those memory locations will still contain the same
values. Hence line 11 outputs 5, because nothing else wrote to those memory
locations.

Having said that, use of a variable after it has been destroyed is undefined
behavior, so technically speaking anything could happen and it would still be
considered "correct" from the compiler's standpoint.

Topic archived. No new replies allowed.