Is there an equivilant of _set_purecall_handler()

2019-08-28 10:19发布

问题:

I wanted to override the standard handler for pure virtual call (__cxa_pure_virtual()) with my own. Answer for Windows is '_set_purecall_handler()'.

Is there a similar facility in Linux/GNU?

回答1:

You came so close to answering this question on your own. This is the source of __cxa_pure_virtual in gcc/libstdc++-v3/libsupc++/pure.cc:

extern "C" void
__cxxabiv1::__cxa_pure_virtual (void)
{
  writestr ("pure virtual method called\n");
  std::terminate ();
}

So, there's no direct equivalent to Microsoft's _set_purecall_handler with GCC. However, since std::terminate is called by this function you can use std::set_terminate to set a handler that gets called after it prints the message.

Another possible solution is to provide your own definition of __cxxabiv1::__cxa_pure_virtual that overrides the library function. Something like this:

namespace __cxxabiv1 {
        extern "C" void
        __cxa_pure_virtual(void) {
                char const msg[] = "my pure virutal\n";
                write(2, msg, sizeof msg - 1);
                std::terminate();
        }
}


回答2:

Without any extra warnings enabled at all g++ (4.5 tested) will tell you that you're calling an abstract function from a constructor/destructor, which should nullify any need to set a custom handler.

Since a valid C++ program would never result in a pure virtual call, I assume you have this handler set on Windows for diagnostic/debugging purposes. In this case it seems far easier to diagnose at compile time rather than runtime.



标签: c++ c linux gcc gnu