且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么是“纯虚拟”的含义?调用堆栈跟踪?

更新时间:2022-10-15 19:30:54

如果实际上调用了一个纯虚函数函数,会导致崩溃。



纯虚函数是一个声明:

  virtual void pureVirtualFunction()= 0; 

通常,编译器会检测您是否忽略实现纯虚函数。但可能会出现这种情况。



在基础构造函数中调用纯虚函数



一常见问题是来自类的基类构造函数的函数调用:

  MyClass :: MyClass(){
pureVirtualFunction(); //从基础构造函数调用纯虚函数。



在基本解构器中调用纯虚函数

或者从基类的解构器中调用纯虚方法:

$ $ $ $ $ $ $ MyClass :: 〜MyClass(){
pureVirtualFunction(); //从基本解构器调用纯虚函数。




$ b

共享指针的转发声明(以及类似的)



如果您使用类似前向声明的话,还有另一种常见情况:

  class MyClass; 
typedef std :: shared_ptr< MyClass> MyClassPtr;

这种共享指针的对象可以在许多地方销毁,但是编译器缺少所需的信息如何调用该类的解构器。确保你读取编译器的所有警告,它会警告这个问题(以及调用纯虚函数的许多其他问题)。



对于这种特殊情况,请确保避免共享指针的前向声明,并仅将它们包含在类声明中(如果可能的话)。



另请参阅answer


My service has crashed and i have got this stack trace. I cannot infer anything from here

00007f859cd27834 __gnu_cxx::__verbose_terminate_handler()
@ 00007f859cd25865 __cxxabiv1::__terminate(void (*)())
@ 00007f859cd25892 std::terminate()
@ 00007f859cd263be __cxa_pure_virtual
@ 0000000001996f9f My::Class::~Class()

Can anyone help?

This happens if actually a "pure virtual" function was called, which results in a crash.

A pure virtual function is one declared:

virtual void pureVirtualFunction() = 0;

Usually the compiler will detect if you omit to implement a pure virtual function. But there can be situations where it can't.

Call of Pure Virtual Function in Base Constructor

One of the common problems are function calls from the base constructor of the class:

MyClass::MyClass() { 
    pureVirtualFunction(); // Call of pure virtual function from base constructor.
}

Call of Pure Virtual Function in Base Deconstructor

Or a call of a pure virtual method from the deconstructor of a base class:

MyClass::~MyClass() { 
    pureVirtualFunction(); // Call of pure virtual function from base deconstructor.
}

Forward Declarations of Shared Pointers (and alike)

There is another common case if you use forward declarations like this:

class MyClass;
typedef std::shared_ptr<MyClass> MyClassPtr;

The object of a such shared pointer can be destroyed at many places, but the compiler lacks the required information how to call the deconstructor of the class. Make sure you read all warnings of the compiler, it will warn about this problem (and about many other problems with calls of pure virtual methods.)

For this special case make sure you avoid forward declarations of shared pointers and include them only with the class declaration (if possible).

See also this answer.