首页 > 代码库 > [转载]析构函数的虚析构和非虚析构调用的差别

[转载]析构函数的虚析构和非虚析构调用的差别

 

 

代码示例:

非虚析构的情况下.

#include <stdio.h>
#include <iostream>

using namespace std;

class A
{
public:
        A()
        {
                std::cout << "A is created." << std::endl;
        }
 
        ~A()
        {
                std::cout << "A is deleted." << std::endl;
        }
};
 
class B : public A
{
public:
        B()
        {
                std::cout << "B is created." << std::endl;
        }
 
        ~B()
        {
                std::cout << "B is deleted." << std::endl;
        }
};

 
int main()
{
    A* pA = new B();
    delete pA;
    return 0;
}

技术分享

虚析构的情况下.

#include <stdio.h>
#include <iostream>

using namespace std;

class A
{
public:
        A()
        {
                std::cout << "A is created." << std::endl;
        }
 
        virtual ~A()
        {
                std::cout << "A is deleted." << std::endl;
        }
};
 
class B : public A
{
public:
        B()
        {
                std::cout << "B is created." << std::endl;
        }
 
        ~B()
        {
                std::cout << "B is deleted." << std::endl;
        }
};

 
int main()
{
    A* pA = new B();
    delete pA;
    return 0;
}

 

技术分享

如果在类型B中创建了一些资源,比如文件句柄、内存等,在这种情况下都得不到释放,从而导致资源泄漏。

[转载]析构函数的虚析构和非虚析构调用的差别