c++ - C++中从虚析构函数调用虚方法

标签 c++ memory-management memory-leaks destructor

<分区>

我想销毁 B 类的对象。

class A {
public:
    A() {
        std::cout << "construct A" << av::endl;
        a = new int;
    }
    virtual ~A() {
        std::cout << "destruct A" << av::endl;
        this->clear();
    }
    virtual void clear() {
        std::cout << "clear A" << av::endl;
        delete a;
    }
protected:
    int *a;
};

class B : public A {
public:
    B() {
        std::cout << "construct B" << av::endl;
        b = new int;
    }
    ~B() {
        std::cout << "destruct B" << av::endl;
    }
    void clear() override {
        std::cout << "clear B" << av::endl;
        delete b;
        delete this->a;
    }
private:
    int *b;
};

我希望使用 clear() 方法来完成。但是当我执行以下代码时:

A *a = new B();
delete a;

我得到:

construct A construct B destruct B destruct A clear A

clear B 永远不会被打印出来。 我做错了什么?

最佳答案

非正式地,在 ~A(); 中 B 部分已经被销毁,调用 B 的任何函数都没有任何意义。


Effective C++ Item 9:永远不要在构造或析构期间调用虚函数。

Once a derived class destructor has run, the object’s derived class data members assume undefined values, so C++ treats them as if they no longer exist. Upon entry to the base class destructor, the object becomes a base class object, and all parts of C++ — virtual functions, dynamic_cast s, etc., —treat it that way.

关于c++ - C++中从虚析构函数调用虚方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42929622/

相关文章:

objective-c - xcode 中泄漏仪器的准确性

c++ - boost "CreateProcess failed"

c++ - 如何检查 LLVM StoreInst 的目标是否为函数指针

c++ - C++在内存的什么地方创建栈和堆?

ios - 分析显示循环的每次迭代中都有泄漏

C:内存泄漏实现一个简单的链表

c++ - win32 c++ 所有者绘制带有透明图像的按钮

c++ - qDeleteAll 和 new[]

c++ - c++ new 运算符可以在 Windows 上自动使用大页面吗?

c - Compiler 是否优化了由 "malloc()"函数分配的内存?