标量类型&的析构函数调用未定义的行为 [英] Destructor call for scalar types & undefined behavior

查看:78
本文介绍了标量类型&的析构函数调用未定义的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚写了以下程序&它会编译&运行良好.(请参见此处的实时演示.)

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;
}

为什么程序可以正常编译?如果我没看错,标量类型在C ++中没有构造函数和析构函数.那么,该程序定义是否正确?在这种情况下,对析构函数的显式调用会破坏 变量a 还是在函数执行完成时由编译器自动销毁?我知道在对象的生命周期结束后访问对象在C ++中具有未定义的行为.但是C ++标准对此有何看法?

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?

我在此处在SO上.@Columbo给出的答案是:

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.

推荐答案

根据:

琐碎的析构函数是不执行任何操作的析构函数.具有琐碎析构函数的对象不需要delete-expression,可以通过简单地重新分配其存储空间来对其进行处理.所有与C语言兼容的数据类型(POD类型)都是微不足道的.

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.

可能与以下事实相似:在C ++中,您可以通过使用(init_val)调用其构造函数,例如 int i(-1);

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.

这篇关于标量类型&amp;的析构函数调用未定义的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆