Destructor call for scalar types & undefined behavior [duplicate]

走远了吗. 提交于 2021-02-08 02:58:09

问题


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.


回答1:


According to this:

A trivial destructor is a destructor that performs no action. Objects with trivial destructors don't require a delete-expression and may be disposed of by simply deallocating their storage. All data types compatible with the C language (POD types) are trivially destructible.

Probably it is similary to the fact that in C++ you can initialize any POD type object like any class type object, by calling its constructor with (init_val) for example int i(-1);

But notice that by definition calling a destructor directly for an ordinary object, such as a local variable, invokes undefined behavior when the destructor is called again, at the end of scope.



来源:https://stackoverflow.com/questions/32217494/destructor-call-for-scalar-types-undefined-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!