显式调用`int`析构函数-为什么需要类型别名? [英] Explicitly invoking `int` destructor - why is a type alias required?

查看:155
本文介绍了显式调用`int`析构函数-为什么需要类型别名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下程序...

int main()
{
    int{1}.~int();
}

不能在上编译(请参见一致性查看器):

  • clang ++干线,带有-std=c++1z

g ++中继,带有-std=c++1z

g++ trunk, with -std=c++1z

CL 19 2017

CL 19 2017

int ...

int main()
{
    using X = int;
    int{1}.~X();
}

...使程序在前面提到的所有编译器上均有效,而不会发出警告(请参阅一致性查看器).

...makes the program valid on all previously mentioned compilers, without warnings (see conformance viewer).

为什么调用int的析构函数时需要类型别名??这是因为int不是用于销毁调用的有效语法元素吗?

Why is a type alias required when invoking int's destructor? Is this because int is not a valid grammar element for a destruction invocation?

推荐答案

它之所以有效,是因为语法没有为内置类型做准备,但为别名做了准备:

It works because the grammar didn't make provisions for built-in types, but it did make provisions for aliases:

[expr.post]/1 :

postfix-expression:
    postfix-expression . pseudo-destructor-name
    postfix-expression -> pseudo-destructor-name

pseudo-destructor-name:
    ~ type-name
    ~ decltype-specifier

[dcl.type.simple]/1 :

type-name:
  class-name
  enum-name
  typedef-name
  simple-template-id

您可以想象type-name下的每个变量代表什么.对于当前情况, [expr.pseudo]/1 指定只是一个void表达式:

You can imagine what each variable under type-name stands for. For the case at hand [expr.pseudo]/1 specifies that it is just a void expression:

在点之后使用伪析构函数名称.或箭头->运算符 表示由类型名称表示的非类类型的析构函数 或decltype-specifier.结果只能用作操作数 对于函数调用运算符(),这样的调用结果具有 输入void.唯一的效果是对postfix-expression的求值 在点或箭头之前.

The use of a pseudo-destructor-name after a dot . or arrow -> operator represents the destructor for the non-class type denoted by type-name or decltype-specifier. The result shall only be used as the operand for the function call operator (), and the result of such a call has type void. The only effect is the evaluation of the postfix-expression before the dot or arrow.

需要注意的有趣一点是,您应该能够在没有别名的情况下(如果有命名对象的情况下)执行此操作,因为伪析构函数调用也可以与decltype说明符一起使用:

The interesting thing to note, is that you should be able do that without an alias (if you have a named object), because the pseudo destructor call also works with a decltype specifier:

auto a = int{1};
a.~decltype(a)();

这篇关于显式调用`int`析构函数-为什么需要类型别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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