pybind / pybind/pybind11

[BUG]: pybind11 should not expect there is always a shared_ptr when detecting enable_shared_from_this

Open
#3,851 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Required prerequisites
Problem description

Currently, when pybind11 detects a class inheriting std::enable_shared_from_this, it asserts users always uses std::shared_ptr to hold it. Specifically, it checks std::shared_ptr::element_type at this line:

https://github.com/pybind/pybind11/blob/47079b9e7b81a4b6d93c46a452115d7d8fd3488f/include/pybind11/pybind11.h#L1784

However, even when a class inherits std::enable_shared_from_this, an object of its does not necessarily be held in a std::shared_ptr. It can be held by std::shared_ptr in just some part of the code, and held by other holders when passing to pybind11. In my case, I warped around std::shared_ptr to build my own holder, which does not have an element_type member type.

A possible fix is to check the type of holder_type first before assuming it is a std::shared_ptr.

Reproducible example code

No response

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 at include/pybind11/pybind11.h around line 1784, where enable_shared_from_this handling inspects the holder type. Trace the surrounding holder and shared_ptr detection logic, then verify that custom holders without an element_type are handled without the assertion; add or update regression coverage if the repository's nearby tests expose this path.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
backend-api-design, devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.