问题描述
在C ++中,以下代码给出了编译器错误:
In C++ the following code gives a compiler error:
void destruct1 (int * item)
{
item->~int();
}
这段代码几乎相同,我只是typedef 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是否只是因为它已经被typedefed得到一个析构函数?
Why does the second code works? Does an int gets a destructor just because it has been typedefed?
如果你想知道为什么有人想这样做:这来自重构C ++代码。我们删除标准堆并用自制池替换它。这需要我们调用placement-new和destructor。我知道调用原始类型的析构函数是无用的,但是我们希望它们在代码中,以防万一我们以后用真实的类替换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.
Btw - 我有一个解决方案涉及模板函数。我们只是在模板里面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
:
使用plain int和typedef'int的区别在于它们在语法上是不同的。规则是,在析构函数调用中,〜
之后的事是类型名。 int
不是这样的东西,但typedef名称是。在 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等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!