Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template function, substitution failure skip the implementation

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;
}
like image 841
r0n9 Avatar asked Mar 13 '14 03:03

r0n9


1 Answers

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.

like image 179
Vince Avatar answered Sep 30 '22 00:09

Vince