c++ - 使用虚拟析构函数会使非虚拟函数进行 v 表查找吗?

标签 c++ oop crtp vtable

正是主题所问的。还想知道为什么 CRTP 的常见示例中没有提到 virtual dtor。

编辑: 伙计们,请也发布有关 CRTP 问题的信息,谢谢。

最佳答案

只有虚函数需要动态调度(因此 vtable 查找),甚至在所有情况下都不需要。如果编译器能够在编译时确定什么是方法调用的最终覆盖,它就可以避免在运行时执行分派(dispatch)。如果需要,用户代码也可以禁用动态调度:

struct base {
   virtual void foo() const { std::cout << "base" << std::endl; }
   void bar() const { std::cout << "bar" << std::endl; }
};
struct derived : base {
   virtual void foo() const { std::cout << "derived" << std::endl; }
};
void test( base const & b ) {
   b.foo();      // requires runtime dispatch, the type of the referred 
                 // object is unknown at compile time.
   b.base::foo();// runtime dispatch manually disabled: output will be "base"
   b.bar();      // non-virtual, no runtime dispatch
}
int main() {
   derived d;
   d.foo();      // the type of the object is known, the compiler can substitute
                 // the call with d.derived::foo()
   test( d );
}

关于是否应该在所有继承情况下都提供虚析构函数,答案是否定的,不一定。仅当代码删除通过指向基类型的指针保存的派生类型的对象时,才需要虚拟析构函数。一般规则是你应该

  • 提供公共(public)虚拟析构函数或 protected 非虚拟析构函数

规则的第二部分确保用户代码不能通过指向基的指针删除您的对象,这意味着析构函数不需要是虚拟的。优点是如果你的类不包含任何虚拟方法,这不会改变你的类的任何属性——当添加第一个虚拟方法时类的内存布局发生变化——你将保存 vtable 指针在每个实例中。从两个原因来看,第一个最重要。

struct base1 {};
struct base2 {
   virtual ~base2() {} 
};
struct base3 {
protected:
   ~base3() {}
};
typedef base1 base;
struct derived : base { int x; };
struct other { int y; };
int main() {
   std::auto_ptr<derived> d( new derived() ); // ok: deleting at the right level
   std::auto_ptr<base> b( new derived() );    // error: deleting through a base 
                                              // pointer with non-virtual destructor
}

main 的最后一行中的问题可以通过两种不同的方式解决。如果 typedef 更改为 base1,则析构函数将正确分派(dispatch)到 derived 对象,并且代码不会导致未定义的行为。代价是 derived 现在需要一个虚拟表并且每个实例都需要一个指针。更重要的是,derived 布局不再与other 兼容。另一个解决方案是将 typedef 更改为 base3,在这种情况下,通过让编译器在该行大喊大叫来解决问题。缺点是不能通过指向base的指针进行删除,优点是编译器可以静态保证不会有undefined behavior。

在 CRTP 模式的特殊情况下(请原谅冗余的 模式),大多数作者甚至不关心使析构函数受到保护,因为其目的不是通过以下方式保存派生类型的对象对基本(模板化)类型的引用。为了安全起见,他们应该将析构函数标记为 protected ,但这很少成为问题。

关于c++ - 使用虚拟析构函数会使非虚拟函数进行 v 表查找吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3923464/

相关文章:

c++ - 如何在 C++ 中使用 jsoncpp 编写嵌套的 json

javascript - 查找对象中的所有变量时出现问题

javascript - Javascript 中的静态变量只设置一次

c++ - 使用通用侵入式指针客户端进行引用计数

c++ - 如何让 std::thread 停止?

c++ - GDB 在操作 SSE2 寄存器时报告 EXC_BAD_ACCESS

c# - 静态字段究竟是如何在内部工作的?

c++ - 问题重构奇怪地重复出现的模板模式

c++ - 为什么我可以使用 CRTP 将基类的 this 指针转换为指向子类的指针?

c++ - 我似乎无法让 Visual C++ Express (2010) 识别枚举类