手动调用基类析构函数和placement new

时间:2017-02-14 13:32:46

标签: c++ destructor new-operator

在破坏使用placement new运算符构造的对象时,在基类指针上调用基类析构函数是否安全?

#include <iostream>

class ABase
{
    public:
    virtual ~ABase()
    {
        std::cout << "~ABase()" << std::endl;
    }
};

class A : public ABase
{
    public:
    ~A()
    {
        std::cout << "~A()" << std::endl;
    }
};

int main()
{
    ABase* a = new (malloc(sizeof(A))) A();
    a->~ABase();
    free(a);
    return 0;
}

输出表明它没问题:

~A()
~ABase()

我在ideone.com上的例子:http://ideone.com/fzhl8x

0 个答案:

没有答案