内置类型(int、char 等)的析构函数

Destructors of builtin types (int, char etc..)(内置类型(int、char 等)的析构函数)

本文介绍了内置类型(int、char 等)的析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++ 中,以下代码给出了编译器错误:

In C++ the following code gives a compiler error:

void destruct1 (int * item)
{
  item->~int();
}

这段代码几乎相同,我只是将 int 类型定义为另一种类型,然后发生了一些神奇的事情:

This code is nearly the same, I just typedef the int to another type and something magic happens:

typedef int myint;

void destruct2 (myint * item)
{
  item->~myint();
}

为什么第二个代码有效?一个 int 是否仅仅因为它被类型定义而得到一个析构函数?

Why does the second code work? Does an int get a destructor just because it has been typedefed?

如果您想知道为什么要这样做:这来自重构 C++ 代码.我们正在移除标准堆并用自制池替换它.这需要我们调用placement-new 和析构函数.我知道为原始类型调用析构函数是没有用的,但我们仍然希望它们在代码中,以防我们以后用真正的类替换 POD.

In case you wonder why one ever would like to do this: This comes from refactoring C++ code. We're removing the standard heap and replacing it with selfmade pools. This requires us to call placement-new and the destructors. I know that calling destructors for primitive types is useless, but we want them in the code nevertheless in case we later replace PODs with real classes.

发现裸 int 不起作用,而 typedefed 却起作用,这真是令人惊讶.

Finding out that naked int's don't work but typedefed ones do was quite a surprise.

顺便说一句 - 我有一个涉及模板函数的解决方案.我们只是在模板中 typedef,一切都很好.

Btw - I have a solution that involves template-functions. We just typedef inside the template and everything is fine.

推荐答案

这是使您的代码适用于泛型参数的原因.考虑一个容器 C:

It's the reason that makes your code work for generic parameters. Consider a container C:

template<typename T>
struct C {
    // ...
    ~C() {
        for(size_t i = 0; i<elements; i++)
            buffer[i].~T();
    }
};

为内置类型引入特殊情况会很烦人.因此 C++ 允许您执行上述操作,即使 T 恰好等于 int.圣典在12.4 p15中说:

It would be annoying to introduce special cases for built-in types. So C++ allows you to do the above, even if T happens to equal to int. The holy Standard says in 12.4 p15:

显式调用析构函数的表示法可用于任何标量类型名称.允许这样做可以编写代码而不必知道给定类型是否存在析构函数.

The notation for explicit call of a destructor can be used for any scalar type name. Allowing this makes it possible to write code without having to know if a destructor exists for a given type.

使用普通 int 和 typedef 的 int 之间的区别在于它们在语法上是不同的.规则是,在析构函数调用中,~ 之后的内容是类型名称.int 不是这样的,但 typedef-name 是.在 7.1.5.2 中查找.

The difference between using a plain int and a typedef'ed int is that they are syntactically different things. The rule is, that in a destructor call, the thing after the ~ is a type-name. int is not such a thing, but a typedef-name is. Look it up in 7.1.5.2.

这篇关于内置类型(int、char 等)的析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:内置类型(int、char 等)的析构函数

基础教程推荐