1

I tried a simple pybind11 example, like this:

// header
class Test
{
private:
    int* m_a;
public:
    Test(int a);
    ~Test();
    int* getA();
};

// cpp
Test::Test(int a){ m_a = new int(a); }
Test::~Test(){ delete m_a; }
int* Test::getA(){ return m_a; }
// bind
namespace py = pybind11;

PYBIND11_MODULE(bindtestlib, m)
{
    py::class_<Test>(m, "Test")
        .def(py::init<int>())
        // as offical guide said, use policy refercence if return bare pointer
        .def("getA", &Test::getA, py::return_value_policy::reference);
}

then import this model in python script

import bindtestlib as bt

t = bt.Test(2)
a = t.getA()
print(a)

run this script will print a's value correctly, but encounter a error before exit pig

then stuck without exit

I tried two ways:

  1. delete the delete m_a in destructor, then script work well, but I think this is a not proper way, may cause memory leak
  2. debug pybind11, found that before Exception occure, stop at different place.

It confused me. I can't figure out what mistake I have made.

  • 2
    You don't need python to show that your `Test` class is faulty: `int main() { Test t1; Test t2; t1 = t2; }` -- just that alone causes a double-deletion error. Look up the [rule of 3](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three), and look at the **Managing resources** section of that answer. – PaulMcKenzie Dec 31 '21 at 04:10
  • @PaulMcKenzie I see, thanks. – Michael_Cache Dec 31 '21 at 06:04

0 Answers0