Enable defining custom __new__ (#3265)

* Enable defining custom __new__

* See if xfail needed

* Qualify auto self

* Unconditionally defining PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING. Returning pointer from "__init__" instead of reference.

* Use new style __init__

* Simplify __new__ creation

* Reviewer suggestions

* Match indentation

Co-authored-by: Ralf W. Grosse-Kunstleve <rwgk@google.com>
This commit is contained in:
Aaron Gokaslan
2021-09-20 10:42:14 -04:00
committed by GitHub
parent 14976c853b
commit d0f3c51f01
3 changed files with 25 additions and 1 deletions

View File

@@ -47,10 +47,25 @@ TEST_SUBMODULE(class_, m) {
}
~NoConstructor() { print_destroyed(this); }
};
struct NoConstructorNew {
NoConstructorNew() = default;
NoConstructorNew(const NoConstructorNew &) = default;
NoConstructorNew(NoConstructorNew &&) = default;
static NoConstructorNew *new_instance() {
auto *ptr = new NoConstructorNew();
print_created(ptr, "via new_instance");
return ptr;
}
~NoConstructorNew() { print_destroyed(this); }
};
py::class_<NoConstructor>(m, "NoConstructor")
.def_static("new_instance", &NoConstructor::new_instance, "Return an instance");
py::class_<NoConstructorNew>(m, "NoConstructorNew")
.def(py::init([](NoConstructorNew *self) { return self; })) // Need a NOOP __init__
.def_static("__new__", [](const py::object *) { return NoConstructorNew::new_instance(); } );
// test_inheritance
class Pet {
public: