好记性不如学 Java
virtual destructor
when-to-use-virtual-destructors from SO
C++ 究竟什么时候该用虚析构函数(virtual destructor)?
Effiective C++ 3rd edition.
Item 7: Declare destructors virtual in polymorphic base classes.
C++ Coding Standards: 101 Rules, Guidelines, and Best Practices
Item 50: Make base class destructors public and virtual, or protected and nonvirtual.
- example:
#include <iostream>
using namespace std;
class Ptr{
public:
~Ptr() {
cout << "Ptr dtor\n";
}
};
class A {
public:
~A() {}
};
class B :public A{
Ptr p;
};
int main ()
{
A *pa = new B();
delete pa;
// 不把 ~A() 声明成 virtual ~Ptr 不会被调用
return 0;
}
- 纯虚析构函数需要提供定义即函数体
smart pointer
make_shared
shared_ptr<Parent> p = make_shared<Child>(...);
shared_ptr
shared_ptr