c++ - 在派生指针上显式调用基类析构函数时编译错误

标签 c++ visual-studio destructor placement-new

正如标题所说。以下人为设计的示例似乎适用于键盘:http://codepad.org/4cgGmvDQ在我的 Linux 机器上的 GCC 4.1.2 下。

#include<stdlib.h>
#include<new>

class IBase
{
public:
    virtual ~IBase(){}
};

class B : public IBase
{
public:
    virtual ~B(){}
};

class D : public B
{
public:
    virtual ~D(){ }
};

int main()
{
    void* p = malloc(sizeof(D));

    D* d = new(p) D();

    B* b = static_cast<B*>(d);

    b->~IBase();

    free(p);
}

但是 Visual Studio Pro 2012 11.0.61030.00 Update 4 失败了:

main.cpp(30): error C2300: 'B': 类没有名为 '~IBase' 的析构函数

显然,可以很容易地重新编写示例来避免该问题,但我的实际代码库没有提供任何其他选项。有人熟悉 Microsoft 编译器的这个特殊故障吗?

最佳答案

这不是 MSVC 中的错误。根据标准,§3.4.5 [basic.lookup.classref]/p2-3(引用 N3936,强调我的):

If the id-expression in a class member access (5.2.5) is an unqualified-id, [...]

If the unqualified-id is ~type-name, the type-name is looked up in the context of the entire postfix-expression. If the type T of the object expression is of a class type C, the type-name is also looked up in the scope of class C. At least one of the lookups shall find a name that refers to (possibly cv-qualified) T.

在您的代码中,TB,查找IBase 显然找不到引用B 的名称。因此,您的代码格式错误。如果 g++ 接受它,它要么是错误要么是扩展。

因为听起来 B 代表的实际类型在您的真实代码中是“不可描述的”,但是 IBase 可以编写,最简单的解决方案就是简单地转换bIBase *

关于c++ - 在派生指针上显式调用基类析构函数时编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25376209/

相关文章:

c++ - 在 C++ 中使用具有私有(private)继承的声明的意外行为

python - 如何实现-在__del__上写入文件?

c++ - 构造函数和析构函数 - C++

c++ - 琐碎的可破坏性和调用析构函数的必要性

同一接口(interface)的多个版本的 C++ 设计(头文件中的枚举/结构)

c++ - 使用 Index 运算符插入带有指向 std::map 的指针的元素

c++ - 当我只有一个指向数据的空指针时,使用 printf 打印字符

c# - IE6 : window. onresize 在 IIS 上工作,在 asp.net 开发服务器上崩溃

c++ - STL中的调试错误

c# - 每次更改 ComboBox(使用 SelectedIndexChanged)时,如果打开,则以其他形式显示具有新值的消息