I just wrote following program & it compiles & runs fine. (see live demo here.)
#include <iostream>
typedef int T;
int main()
{
int a=3;
std::cout<<a<<'\n';
a.~T();
std::cout<<a;
return 0;
}
Why the program compiles fine?
If I am not wrong scalar types don't have constructor and destructor in C++. So, is this program well defined? Does explicit call to destructor destroys variable a
in this case or it will be automatically destroyed by compiler when execution of function completes? I know that accessing an object after its lifetime has ended has undefined behaviour in C++. But what the C++ standard says about this?
I found little similar question here on SO. The answer given by @Columbo says that:
You can't call a destructor for scalar types, because they don't have one. The statement is solely allowed for template code in which you call the destructor of an object whose type you don't know - it removes the necessity of writing a specialization for scalar (or even array) types.
So, I don't understand the explanation given by him. It would be better if someone explains it using template code in which destructor is called of an object whose type isn't known. I would be thankful if someone explains this using simple example.
typedef
)? Both g++ and clang++ don't complain though... – Metaphor