gpt4 book ai didi

c++ - typedef 别名的析构函数

转载 作者:IT老高 更新时间:2023-10-28 21:41:17 26 4
gpt4 key购买 nike

#include <iostream>

struct A { ~A(); };
A::~A() {
std::cout << "Destructor was called!" << std::endl;
}

typedef A AB;
int main() {
AB x;
x.AB::~AB(); // Why does this work?
x.AB::~A();
}

上述程序的输出为:

Destructor was called!
Destructor was called!
Destructor was called!

我假设前两行属于用户析构函数调用,而第三行是由于退出 main 函数范围时调用析构函数。

据我了解,typedef 是类型的别名。在这种情况下,ABA 的别名。

为什么这也适用于析构函数的名称?非常感谢您引用语言规范。

编辑:这是在 macOS High Sierra 版本 10.13.3 上使用 Apple LLVM 版本 9.1.0 (clang-902.0.39.1) 编译的。

最佳答案

Why does this apply for the name of the destructor too?

因为标准说:

[class.dtor]

In an explicit destructor call, the destructor is specified by a ~ followed by a type-name or decltype-specifier that denotes the destructor’s class type. ...

typedef 别名是一个类型名,它表示与类本身的类型名相同的类。

该规则甚至有一个明确的例子:

struct B {
virtual ~B() { }
};
struct D : B {
~D() { }
};

D D_object;
typedef B B_alias;
B* B_ptr = &D_object;

void f() {
D_object.B::~B(); // calls B's destructor
B_ptr->~B(); // calls D's destructor
B_ptr->~B_alias(); // calls D's destructor
B_ptr->B_alias::~B(); // calls B's destructor
B_ptr->B_alias::~B_alias(); // calls B's destructor
}

关于名称查找的进一步说明,以及适用于该问题的示例:

[basic.lookup.qual]

If a pseudo-destructor-name ([expr.pseudo]) contains a nested-name-specifier, the type-names are looked up as types in the scope designated by the nested-name-specifier. Similarly, in a qualified-id of the form:

nested-name-specifieropt class-name :: ~ class-name

the second class-name is looked up in the same scope as the first. [ Example:

struct C {
typedef int I;
};
typedef int I1, I2;
extern int* p;
extern int* q;
p->C::I::~I(); // I is looked up in the scope of C
q->I1::~I2(); // I2 is looked up in the scope of the postfix-expression

struct A {
~A();
};
typedef A AB;
int main() {
AB* p;
p->AB::~AB(); // explicitly calls the destructor for A
}

— end example  ]

关于c++ - typedef 别名的析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52256851/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com