pybind / pybind/pybind11

Shared Pointers and Protected Destructors

Open
#1,178 8 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C++
Stars
18k
Forks
2.3k
Avg merge
5d 17h
Merged PRs (30d)
10

Description

I am trying to wrap a C++ class of the following type. The class has a protected destructor but should be containable in a shared_ptr due to the public inheritance from enable_shared_from_this. However, the pybind code produces an error becuase of the protected destructor.

The code also throws an error if I try to use the following pybind wrapper:
py::class_<MyClass, std::unique_ptr<MyClass, py::nodelete>> clsMyClass(mod, "MyClass");

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>

namespace py = pybind11;
namespace {

class MyClass : public std::enable_shared_from_this<MyClass> {
protected:
	MyClass() {}
	~MyClass() {}
};

PYBIND11_MODULE(myclass, mod) {
    py::class_<MyClass, std::shared_ptr<MyClass>> clsMyClass(mod, "MyClass");
}
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the py::class_ declarations in the PYBIND11_MODULE example, comparing the std::shared_ptr holder with the std::unique_ptr and py::nodelete variant. Reproduce the protected-destructor error and determine what behavior is expected for a class using enable_shared_from_this; done means the supported wrapping form is clear and the example no longer produces that error.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.