I have following code just for testing, the template function is used twice, the first time it is ok. In second case, I create a pointer and pass the pointer as a reference into the template function. I expected the line "obj.~T()" failed compile time. But actually the code compiles and runs fine. When I debug through the function, the program simply skip the obj.~T(); I am using VC10.
My question is:
1. Is this a expected behavior? If it is based on which section from the c++ standrade?
2. Any pro and con about this behavior??? In my case it is good since no compile error neither run time error. But there might be some situation I do not know but do damage the code.
Thanks
template<typename T>
void ptrDest(T& obj)
{
obj.~T();
}
class Dummy
{
public:
Dummy(){}
~Dummy(){ cout << "dest" <<endl;}
};
int main()
{
Dummy d;
ptrDest(d);
Dummy* pd = new Dummy();
ptrDest(pd);
return 0;
}
This is an explicit destructor call, and it is a valid operation, although not necessarily considered a good practice. Think of using scoped variables instead, if possible.
In your second call, you are actually trying to call the destructor of the pointer, which indeed does not exists, instead of the destructor of the pointed object, and this is why it skips it. Be advised, though, that your Dummy object is still allocated after the second call, and you will leak in all circumstances.
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