pybind / pybind/pybind11

[QUESTION] how to def constructor when operator new is deleted in class?

Open
#2,852 10 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

pybind is amazing, but I still have some problems, E.g. py::init alway call new to create instance;

but if the following code

class Example {
private:
	Example(int) {}; // private constructor
public:
	void* operator new(size_t) = delete;
	// Factory function:
	static Example create(int a) { return Example(a); }
};

py::class_<Example>(m, "Example")
    .def(py::init(&Example::create));

how to def constructor?

EDIT (@YannickJadoul): code block with ```c++

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 Example class and the py::class_(m, "Example").def(py::init(&Example::create)) snippet. Trace how py::init constructs bound instances and determine whether a factory returning Example can be used when operator new is deleted; done means establishing a supported binding approach or documenting that this case is unsupported.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
api
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.