boost::python::pure_virtual的实际用途是什么?何时应当使用?
boost::python::pure_virtual and what's its actual purpose? Great question! It's totally normal to be confused when your code works fine both with and without pure_virtual—let's break down what this tool actually does and when you need it.
1. Core Purpose: Enforce Python Subclasses to Implement Pure Virtual Functions
When you mark a member function with pure_virtual, Boost.Python adds a critical check at the Python subclass instantiation stage: it forces any Python subclass to override the function, otherwise it throws a TypeError immediately.
For example, without pure_virtual, this broken Python code would compile but crash at runtime:
class BadA(A): pass # No implementation of f() bad_a = BadA() bad_a.f() # Crashes because it tries to call the unimplemented pure virtual function
But with pure_virtual applied to A::f, instantiating BadA would throw an error right away:
TypeError: Cannot instantiate abstract class 'BadA' with abstract method 'f'
This catches mistakes early instead of letting your program crash unexpectedly.
2. Why Your Example Works Without It
In your code, both your C++ subclass B and Python subclass A2 properly implement f(). Since there's always a valid implementation to dispatch to, the absence of pure_virtual doesn't cause issues. The problem only arises when someone creates a Python subclass that fails to override the pure virtual function.
3. Secondary Benefit: Optimized Dispatch
pure_virtual also gives Boost.Python a hint that this function is purely virtual, allowing it to skip some redundant checks during function dispatch. While this performance gain is minor, it can add up in high-frequency call scenarios.
When You Should Definitely Use It
- To enforce interface compliance: If you want Python users to be forced to implement the function (just like the C++ pure virtual requirement),
pure_virtualis non-negotiable—it prevents silent runtime crashes. - For clearer API contracts: Explicitly marking the function as pure virtual makes your Boost.Python wrapper's intent obvious to other developers working with the code.
- To avoid undefined behavior: Without it, calling an unimplemented pure virtual function from Python leads to undefined behavior (usually a crash), which is hard to debug.
pure_virtualturns this into a clear, catchable exception.
内容的提问来源于stack exchange,提问作者Holt

