为什么共享指针有虚函数
why shared pointer has a virtual function
Scott Meyer 的书中提到,使用共享指针导致的部分开销是它们需要 virutal 函数来正确销毁指向的对象。我的问题是为什么?这不应该是那个指向对象的 class 具有虚拟析构函数的责任吗?
Is this not supposed to be the reponsibility of the class of that pointed object to have a virtual destructor?
那是设计共享指针的一种可能方法,但是 std::shared_ptr
允许您执行以下操作,即使 Base
没有虚拟析构函数:
std::shared_ptr<Base> p { new Derived{} };
它通过在构造 std::shared_ptr
时为参数捕获正确的删除器来实现这一点,然后在引用计数为零时调用它而不是仅仅使用 delete
(当然,你可以传递您自己的自定义删除器来代替使用)。这通常被称为类型擦除,并且这种技术通常使用虚函数调用来实现。
Scott Meyer 的书中提到,使用共享指针导致的部分开销是它们需要 virutal 函数来正确销毁指向的对象。我的问题是为什么?这不应该是那个指向对象的 class 具有虚拟析构函数的责任吗?
Is this not supposed to be the reponsibility of the class of that pointed object to have a virtual destructor?
那是设计共享指针的一种可能方法,但是 std::shared_ptr
允许您执行以下操作,即使 Base
没有虚拟析构函数:
std::shared_ptr<Base> p { new Derived{} };
它通过在构造 std::shared_ptr
时为参数捕获正确的删除器来实现这一点,然后在引用计数为零时调用它而不是仅仅使用 delete
(当然,你可以传递您自己的自定义删除器来代替使用)。这通常被称为类型擦除,并且这种技术通常使用虚函数调用来实现。