Learn a C++ tip every day. Clause 07: Declare a polymorphic base class as a virtual destructor

This blog post and this series are my thoughts on watching "Effective C++", and I learn a little trick to improve my C++ every day.

Item 07: Declare a virtual destructor for a polymorphic base class

When using polymorphism, if there are properties in the subclass that are opened to the heap area, then the parent class pointer cannot be called to the subclass's destructor code when it is released, and the keyword virtual is added to the virtual function of the parent class.

class Animal {
    
    
public:

	Animal()
	{
    
    
		cout << "Animal 构造函数调用!" << endl;
	}
	virtual void Speak() = 0;

	//析构函数加上virtual关键字,变成虚析构函数
	//virtual ~Animal()
	//{
    
    
	//	cout << "Animal虚析构函数调用!" << endl;
	//}


	virtual ~Animal() = 0;
};

Animal::~Animal()
{
    
    
	cout << "Animal 纯虚析构函数调用!" << endl;
}

//和包含普通纯虚函数的类一样,包含了纯虚析构函数的类也是一个抽象类。不能够被实例化。

class Cat : public Animal {
    
    
public:
	Cat(string name)
	{
    
    
		cout << "Cat构造函数调用!" << endl;
		m_Name = new string(name);
	}
	virtual void Speak()
	{
    
    
		cout << *m_Name << "小猫在说话!" << endl;
	}
	~Cat()
	{
    
    
		cout << "Cat析构函数调用!" << endl;
		if (this->m_Name != NULL) {
    
    
			delete m_Name;
			m_Name = NULL;
		}
	}

public:
	string* m_Name;
};

class Dog : public Animal {
    
    
public:
	Dog(string name)
	{
    
    
		cout << "Dog构造函数调用!" << endl;
		m_Name = new string(name);
	}
	virtual void Speak()
	{
    
    
		cout << *m_Name << "小狗在说话!" << endl;
	}
	~Dog()
	{
    
    
		cout << "Dog析构函数调用!" << endl;
		if (this->m_Name != NULL) {
    
    
			delete m_Name;
			m_Name = NULL;
		}
	}

public:
	string* m_Name;
};

void test01()
{
    
    
	Animal* animal1 = new Cat("Tom");
	
	animal1->Speak();//调用cat的speak函数

	//通过父类指针去释放,会导致子类对象可能清理不干净,造成内存泄漏
	//怎么解决?给基类增加一个虚析构函数
	//虚析构函数就是用来解决通过父类指针释放子类对象
	delete animal1;

	cout << endl;
	Animal* animal2 = new Dog("Ben");
	animal2->Speak();//调用dog的speak函数
	delete animal2;
}

Effect at runtime

Insert picture description here

  • C++'s virtual function will produce runtime polymorphism and achieve the effect of late binding, so many C++ design patterns are around virtual.
  • All declared as virtual functions carry a virtual function table pointer which occupies 4 bits in a 32-bit system.

remember:

The base class with polymorphism should declare a virtual (virtual) destructor. If the class has any virtual functions, it should have a virtual destructor.
The design purpose of the class is not to be used as a base class, or to have polymorphism, so virtual destructors should not be declared.

Guess you like

Origin blog.csdn.net/weixin_50188452/article/details/111302194