pybind11中受保护的虚拟析构函数

时间:2019-05-21 14:13:41

标签: c++ pybind11

我想与第三方库中的类绑定。该类具有一些纯虚函数,但析构函数是受保护的且是虚的。

为了绑定该类,我必须编写一个派生类来覆盖纯虚函数(https://pybind11.readthedocs.io/en/stable/advanced/classes.html

所以代码是这样的

class Parent {  
  public:  
    virtual void foo() = 0;
  protected:
    virtual ~ Parent() //Dtor
    {
    }
};

class PyParent : public Parent 
{
  public:
    void foo () override {
        PYBIND11_OVERLOAD_PURE(
            void,
            Parent,
            foo
        );
    }
};

void init(py::module & m) {
    py::class_<Parent, PyParent> p(m, "p");
}

但是,由于基类的析构函数被声明为受保护的,因此将引发以下错误

error: ‘virtual Parent::~Parent()’ is protected
         virtual ~ Parent() //Dtor

由于它是第三方库,因此我无法修改基类。

有什么想法要用pybind11绑定类吗?

1 个答案:

答案 0 :(得分:1)

lst = [] current= [] for i in range(3): print(current) print(lst) lst.append(current[:]) # shallow-copy print(lst) current.append(i) std::unique_ptr是pybind开箱即用支持的智能指针。他们两个都要求析构函数公开。

最简单的解决方案是使用公共析构函数编写中间类,并使用pybind11公开它。

std::shared_ptr

因此,您所有的Python类都将从... class DeletableParent : public Parent{ public: ~DeletableParent() override = default; }; ... py::class_<DeletableParent, PyParent> p(m, "p"); 继承

如果您要做的只是在Python方面制作Parent派生的类,则此解决方案很好。

如果您想公开一个没有DeletableParent作为其基础之一的C ++ Parent-derived-class,那么在公开这种分散的继承关系时会遇到困难。

另一种选择是编写自己的智能指针,该智能指针不调用保持指针的析构函数。但这似乎是内存泄漏的直接途径。

更新: 我忽略了pybind11 doc中已经涵盖了这个特定问题: https://pybind11.readthedocs.io/en/stable/advanced/classes.html#non-public-destructors

相关问题