为什么禁止使用析构函数的地址? [英] Why is taking the address of a destructor forbidden?

查看:123
本文介绍了为什么禁止使用析构函数的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

12.4.2的C ++标准指出

C++ standard at 12.4.2 states that

[...]不应使用析构函数的地址. [...]

[...] The address of a destructor shall not be taken. [...]

但是,编译器可以毫无怨言地获取围绕类析构函数的包装器地址,如下所示:

However, one can without any complaints by the compiler take the address of a wrapper around a class destructor, like this:

struct Test {
    ~Test(){};

    void destructor(){
        this->~Test();
    }
};

void (Test::*d)() = &Test::destructor;

那么禁止直接使用析构函数的地址的背后原理是什么?

So what's the rationale behind forbidding to take the address of a destructor directly?

推荐答案

构造函数和析构函数有些特殊.编译器经常 在调用它们时使用不同的约定(例如,传递额外的隐藏 参数).如果您将地址保存在某个地方, 编译器会丢失该函数是构造函数的信息 或析构函数,并且不知道使用特殊约定.

Constructors and destructors are somewhat special. The compiler often uses different conventions when calling them (e.g. to pass extra hidden arguments). If you took the address and saved it somewhere, the compiler would lose the information that the function is a constructor or destructor, and would not know to use the special conventions.

这篇关于为什么禁止使用析构函数的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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