C++小记 [持续更新中]

Enochii published at 2021-01-02

好记性不如学 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.

#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 是个好东西!`void*` yyds!type erasure!

SO link