Automatic pre-commit run --all-files and clang-tidy changes (NO manual changes).

This commit is contained in:
Ralf W. Grosse-Kunstleve 2022-02-14 19:00:40 -08:00
parent d5e302ce46
commit 05c8b9b7a8
36 changed files with 237 additions and 228 deletions

View File

@ -206,9 +206,10 @@ void construct(value_and_holder &v_h, std::unique_ptr<Cpp<Class>, D> &&unq_ptr,
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias); PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);
auto *ptr = unq_ptr.get(); auto *ptr = unq_ptr.get();
no_nullptr(ptr); no_nullptr(ptr);
if (PYBIND11_SILENCE_MSVC_C4127(Class::has_alias) && need_alias && !is_alias<Class>(ptr)) if (PYBIND11_SILENCE_MSVC_C4127(Class::has_alias) && need_alias && !is_alias<Class>(ptr)) {
throw type_error("pybind11::init(): construction failed: returned std::unique_ptr pointee " throw type_error("pybind11::init(): construction failed: returned std::unique_ptr pointee "
"is not an alias instance"); "is not an alias instance");
}
// Here and below: if the new object is a trampoline, the shared_from_this mechanism needs // Here and below: if the new object is a trampoline, the shared_from_this mechanism needs
// to be prevented from accessing the smart_holder vptr, because it does not keep the // to be prevented from accessing the smart_holder vptr, because it does not keep the
// trampoline Python object alive. For types that don't inherit from enable_shared_from_this // trampoline Python object alive. For types that don't inherit from enable_shared_from_this
@ -242,9 +243,10 @@ void construct(value_and_holder &v_h, std::shared_ptr<Cpp<Class>> &&shd_ptr, boo
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias); PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);
auto *ptr = shd_ptr.get(); auto *ptr = shd_ptr.get();
no_nullptr(ptr); no_nullptr(ptr);
if (PYBIND11_SILENCE_MSVC_C4127(Class::has_alias) && need_alias && !is_alias<Class>(ptr)) if (PYBIND11_SILENCE_MSVC_C4127(Class::has_alias) && need_alias && !is_alias<Class>(ptr)) {
throw type_error("pybind11::init(): construction failed: returned std::shared_ptr pointee " throw type_error("pybind11::init(): construction failed: returned std::shared_ptr pointee "
"is not an alias instance"); "is not an alias instance");
}
auto smhldr = type_caster<Cpp<Class>>::template smart_holder_from_shared_ptr(shd_ptr); auto smhldr = type_caster<Cpp<Class>>::template smart_holder_from_shared_ptr(shd_ptr);
v_h.value_ptr() = ptr; v_h.value_ptr() = ptr;
v_h.type->init_instance(v_h.inst, &smhldr); v_h.type->init_instance(v_h.inst, &smhldr);

View File

@ -74,9 +74,10 @@ struct guarded_delete {
guarded_delete(void (*del_ptr)(void *), bool armed_flag) guarded_delete(void (*del_ptr)(void *), bool armed_flag)
: del_ptr{del_ptr}, armed_flag{armed_flag} {} : del_ptr{del_ptr}, armed_flag{armed_flag} {}
void operator()(void *raw_ptr) const { void operator()(void *raw_ptr) const {
if (armed_flag) if (armed_flag) {
(*del_ptr)(raw_ptr); (*del_ptr)(raw_ptr);
} }
}
}; };
template <typename T, typename std::enable_if<std::is_destructible<T>::value, int>::type = 0> template <typename T, typename std::enable_if<std::is_destructible<T>::value, int>::type = 0>
@ -138,10 +139,11 @@ struct smart_holder {
template <typename T> template <typename T>
static void ensure_pointee_is_destructible(const char *context) { static void ensure_pointee_is_destructible(const char *context) {
if (!std::is_destructible<T>::value) if (!std::is_destructible<T>::value) {
throw std::invalid_argument(std::string("Pointee is not destructible (") + context throw std::invalid_argument(std::string("Pointee is not destructible (") + context
+ ")."); + ").");
} }
}
void ensure_is_populated(const char *context) const { void ensure_is_populated(const char *context) const {
if (!is_populated) { if (!is_populated) {
@ -207,7 +209,7 @@ struct smart_holder {
} }
void reset_vptr_deleter_armed_flag(bool armed_flag) const { void reset_vptr_deleter_armed_flag(bool armed_flag) const {
auto vptr_del_ptr = std::get_deleter<guarded_delete>(vptr); auto *vptr_del_ptr = std::get_deleter<guarded_delete>(vptr);
if (vptr_del_ptr == nullptr) { if (vptr_del_ptr == nullptr) {
throw std::runtime_error( throw std::runtime_error(
"smart_holder::reset_vptr_deleter_armed_flag() called in an invalid context."); "smart_holder::reset_vptr_deleter_armed_flag() called in an invalid context.");
@ -249,10 +251,11 @@ struct smart_holder {
ensure_pointee_is_destructible<T>("from_raw_ptr_take_ownership"); ensure_pointee_is_destructible<T>("from_raw_ptr_take_ownership");
smart_holder hld; smart_holder hld;
auto gd = make_guarded_builtin_delete<T>(true); auto gd = make_guarded_builtin_delete<T>(true);
if (void_cast_raw_ptr) if (void_cast_raw_ptr) {
hld.vptr.reset(static_cast<void *>(raw_ptr), std::move(gd)); hld.vptr.reset(static_cast<void *>(raw_ptr), std::move(gd));
else } else {
hld.vptr.reset(raw_ptr, std::move(gd)); hld.vptr.reset(raw_ptr, std::move(gd));
}
hld.vptr_is_using_builtin_delete = true; hld.vptr_is_using_builtin_delete = true;
hld.is_populated = true; hld.is_populated = true;
return hld; return hld;
@ -301,14 +304,16 @@ struct smart_holder {
hld.rtti_uqp_del = &typeid(D); hld.rtti_uqp_del = &typeid(D);
hld.vptr_is_using_builtin_delete = is_std_default_delete<T>(*hld.rtti_uqp_del); hld.vptr_is_using_builtin_delete = is_std_default_delete<T>(*hld.rtti_uqp_del);
guarded_delete gd{nullptr, false}; guarded_delete gd{nullptr, false};
if (hld.vptr_is_using_builtin_delete) if (hld.vptr_is_using_builtin_delete) {
gd = make_guarded_builtin_delete<T>(true); gd = make_guarded_builtin_delete<T>(true);
else } else {
gd = make_guarded_custom_deleter<T, D>(true); gd = make_guarded_custom_deleter<T, D>(true);
if (void_cast_raw_ptr) }
if (void_cast_raw_ptr) {
hld.vptr.reset(static_cast<void *>(unq_ptr.get()), std::move(gd)); hld.vptr.reset(static_cast<void *>(unq_ptr.get()), std::move(gd));
else } else {
hld.vptr.reset(unq_ptr.get(), std::move(gd)); hld.vptr.reset(unq_ptr.get(), std::move(gd));
}
(void) unq_ptr.release(); (void) unq_ptr.release();
hld.is_populated = true; hld.is_populated = true;
return hld; return hld;

View File

@ -38,7 +38,7 @@ inline void register_instance(instance *self, void *valptr, const type_info *tin
inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo); inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo);
// Replace all occurrences of a character in string. // Replace all occurrences of a character in string.
inline void replace_all(std::string& str, const std::string& from, char to) { inline void replace_all(std::string &str, const std::string &from, char to) {
size_t pos = str.find(from); size_t pos = str.find(from);
while (pos != std::string::npos) { while (pos != std::string::npos) {
str.replace(pos, from.length(), 1, to); str.replace(pos, from.length(), 1, to);
@ -51,11 +51,12 @@ inline void replace_all(std::string& str, const std::string& from, char to) {
// held value, while the modified implementation propagates value_and_holder. // held value, while the modified implementation propagates value_and_holder.
class modified_type_caster_generic_load_impl { class modified_type_caster_generic_load_impl {
public: public:
PYBIND11_NOINLINE explicit modified_type_caster_generic_load_impl(const std::type_info &type_info) PYBIND11_NOINLINE explicit modified_type_caster_generic_load_impl(
: typeinfo(get_type_info(type_info)), cpptype(&type_info) { } const std::type_info &type_info)
: typeinfo(get_type_info(type_info)), cpptype(&type_info) {}
explicit modified_type_caster_generic_load_impl(const type_info *typeinfo = nullptr) explicit modified_type_caster_generic_load_impl(const type_info *typeinfo = nullptr)
: typeinfo(typeinfo), cpptype(typeinfo ? typeinfo->cpptype : nullptr) { } : typeinfo(typeinfo), cpptype(typeinfo ? typeinfo->cpptype : nullptr) {}
bool load(handle src, bool convert) { bool load(handle src, bool convert) {
return load_impl<modified_type_caster_generic_load_impl>(src, convert); return load_impl<modified_type_caster_generic_load_impl>(src, convert);
@ -70,20 +71,19 @@ public:
// Lazy allocation for unallocated values: // Lazy allocation for unallocated values:
if (vptr == nullptr) { if (vptr == nullptr) {
// Lazy allocation for unallocated values: // Lazy allocation for unallocated values:
auto *type = v_h.type ? v_h.type : typeinfo; const auto *type = v_h.type ? v_h.type : typeinfo;
if (type->operator_new) { if (type->operator_new) {
vptr = type->operator_new(type->type_size); vptr = type->operator_new(type->type_size);
} else { } else {
#if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912) #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
if (type->type_align > __STDCPP_DEFAULT_NEW_ALIGNMENT__) { if (type->type_align > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
vptr = ::operator new(type->type_size, vptr = ::operator new(type->type_size, std::align_val_t(type->type_align));
std::align_val_t(type->type_align));
} else { } else {
vptr = ::operator new(type->type_size); vptr = ::operator new(type->type_size);
} }
#else #else
vptr = ::operator new(type->type_size); vptr = ::operator new(type->type_size);
#endif #endif
} }
} }
// type_caster_generic::load_value END // type_caster_generic::load_value END
@ -93,7 +93,7 @@ public:
} }
bool try_implicit_casts(handle src, bool convert) { bool try_implicit_casts(handle src, bool convert) {
for (auto &cast : typeinfo->implicit_casts) { for (const auto &cast : typeinfo->implicit_casts) {
modified_type_caster_generic_load_impl sub_caster(*cast.first); modified_type_caster_generic_load_impl sub_caster(*cast.first);
if (sub_caster.load(src, convert)) { if (sub_caster.load(src, convert)) {
if (loaded_v_h_cpptype != nullptr) { if (loaded_v_h_cpptype != nullptr) {
@ -129,12 +129,11 @@ public:
std::string as_void_ptr_function_name("as_"); std::string as_void_ptr_function_name("as_");
as_void_ptr_function_name += type_name; as_void_ptr_function_name += type_name;
if (hasattr(src, as_void_ptr_function_name.c_str())) { if (hasattr(src, as_void_ptr_function_name.c_str())) {
auto as_void_ptr_function = function( auto as_void_ptr_function = function(src.attr(as_void_ptr_function_name.c_str()));
src.attr(as_void_ptr_function_name.c_str()));
auto void_ptr_capsule = as_void_ptr_function(); auto void_ptr_capsule = as_void_ptr_function();
if (isinstance<capsule>(void_ptr_capsule)) { if (isinstance<capsule>(void_ptr_capsule)) {
unowned_void_ptr_from_void_ptr_capsule = reinterpret_borrow<capsule>( unowned_void_ptr_from_void_ptr_capsule
void_ptr_capsule).get_pointer(); = reinterpret_borrow<capsule>(void_ptr_capsule).get_pointer();
return true; return true;
} }
} }
@ -159,24 +158,26 @@ public:
PYBIND11_NOINLINE bool try_load_foreign_module_local(handle src) { PYBIND11_NOINLINE bool try_load_foreign_module_local(handle src) {
constexpr auto *local_key = PYBIND11_MODULE_LOCAL_ID; constexpr auto *local_key = PYBIND11_MODULE_LOCAL_ID;
const auto pytype = type::handle_of(src); const auto pytype = type::handle_of(src);
if (!hasattr(pytype, local_key)) if (!hasattr(pytype, local_key)) {
return false; return false;
}
type_info *foreign_typeinfo = reinterpret_borrow<capsule>(getattr(pytype, local_key)); type_info *foreign_typeinfo = reinterpret_borrow<capsule>(getattr(pytype, local_key));
// Only consider this foreign loader if actually foreign and is a loader of the correct cpp type // Only consider this foreign loader if actually foreign and is a loader of the correct cpp
// type
if (foreign_typeinfo->module_local_load == &local_load if (foreign_typeinfo->module_local_load == &local_load
|| (cpptype && !same_type(*cpptype, *foreign_typeinfo->cpptype))) || (cpptype && !same_type(*cpptype, *foreign_typeinfo->cpptype))) {
return false; return false;
}
void* foreign_loader_void_ptr = void *foreign_loader_void_ptr
foreign_typeinfo->module_local_load(src.ptr(), foreign_typeinfo); = foreign_typeinfo->module_local_load(src.ptr(), foreign_typeinfo);
if (foreign_loader_void_ptr != nullptr) { if (foreign_loader_void_ptr != nullptr) {
auto foreign_loader = std::unique_ptr<modified_type_caster_generic_load_impl>( auto foreign_loader = std::unique_ptr<modified_type_caster_generic_load_impl>(
static_cast<modified_type_caster_generic_load_impl *>(foreign_loader_void_ptr)); static_cast<modified_type_caster_generic_load_impl *>(foreign_loader_void_ptr));
// Magic number intentionally hard-coded for simplicity and maximum robustness. // Magic number intentionally hard-coded for simplicity and maximum robustness.
if (foreign_loader->local_load_safety_guard != 1887406645) { if (foreign_loader->local_load_safety_guard != 1887406645) {
pybind11_fail( pybind11_fail("smart_holder_type_casters: Unexpected local_load_safety_guard,"
"smart_holder_type_casters: Unexpected local_load_safety_guard,"
" possibly due to py::class_ holder mixup."); " possibly due to py::class_ holder mixup.");
} }
if (loaded_v_h_cpptype != nullptr) { if (loaded_v_h_cpptype != nullptr) {
@ -196,11 +197,15 @@ public:
// logic (without having to resort to virtual inheritance). // logic (without having to resort to virtual inheritance).
template <typename ThisT> template <typename ThisT>
PYBIND11_NOINLINE bool load_impl(handle src, bool convert) { PYBIND11_NOINLINE bool load_impl(handle src, bool convert) {
if (!src) return false; if (!src) {
return false;
}
if (cpptype && try_as_void_ptr_capsule(src)) { if (cpptype && try_as_void_ptr_capsule(src)) {
return true; return true;
} }
if (!typeinfo) return try_load_foreign_module_local(src); if (!typeinfo) {
return try_load_foreign_module_local(src);
}
auto &this_ = static_cast<ThisT &>(*this); auto &this_ = static_cast<ThisT &>(*this);
@ -209,12 +214,13 @@ public:
// Case 1: If src is an exact type match for the target type then we can reinterpret_cast // Case 1: If src is an exact type match for the target type then we can reinterpret_cast
// the instance's value pointer to the target type: // the instance's value pointer to the target type:
if (srctype == typeinfo->type) { if (srctype == typeinfo->type) {
this_.load_value_and_holder(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder()); this_.load_value_and_holder(
reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
return true; return true;
} }
// Case 2: We have a derived class // Case 2: We have a derived class
if (PyType_IsSubtype(srctype, typeinfo->type)) { if (PyType_IsSubtype(srctype, typeinfo->type)) {
auto &bases = all_type_info(srctype); // subtype bases const auto &bases = all_type_info(srctype); // subtype bases
bool no_cpp_mi = typeinfo->simple_type; bool no_cpp_mi = typeinfo->simple_type;
// Case 2a: the python type is a Python-inherited derived class that inherits from just // Case 2a: the python type is a Python-inherited derived class that inherits from just
@ -224,18 +230,21 @@ public:
// is extremely common, we handle it specially to avoid the loop iterator and type // is extremely common, we handle it specially to avoid the loop iterator and type
// pointer lookup overhead) // pointer lookup overhead)
if (bases.size() == 1 && (no_cpp_mi || bases.front()->type == typeinfo->type)) { if (bases.size() == 1 && (no_cpp_mi || bases.front()->type == typeinfo->type)) {
this_.load_value_and_holder(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder()); this_.load_value_and_holder(
reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
loaded_v_h_cpptype = bases.front()->cpptype; loaded_v_h_cpptype = bases.front()->cpptype;
reinterpret_cast_deemed_ok = true; reinterpret_cast_deemed_ok = true;
return true; return true;
} }
// Case 2b: the python type inherits from multiple C++ bases. Check the bases to see if // Case 2b: the python type inherits from multiple C++ bases. Check the bases to see
// we can find an exact match (or, for a simple C++ type, an inherited match); if so, we // if we can find an exact match (or, for a simple C++ type, an inherited match); if
// can safely reinterpret_cast to the relevant pointer. // so, we can safely reinterpret_cast to the relevant pointer.
if (bases.size() > 1) { if (bases.size() > 1) {
for (auto base : bases) { for (auto *base : bases) {
if (no_cpp_mi ? PyType_IsSubtype(base->type, typeinfo->type) : base->type == typeinfo->type) { if (no_cpp_mi ? PyType_IsSubtype(base->type, typeinfo->type)
this_.load_value_and_holder(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder(base)); : base->type == typeinfo->type) {
this_.load_value_and_holder(
reinterpret_cast<instance *>(src.ptr())->get_value_and_holder(base));
loaded_v_h_cpptype = base->cpptype; loaded_v_h_cpptype = base->cpptype;
reinterpret_cast_deemed_ok = true; reinterpret_cast_deemed_ok = true;
return true; return true;
@ -243,9 +252,9 @@ public:
} }
} }
// Case 2c: C++ multiple inheritance is involved and we couldn't find an exact type match // Case 2c: C++ multiple inheritance is involved and we couldn't find an exact type
// in the registered bases, above, so try implicit casting (needed for proper C++ casting // match in the registered bases, above, so try implicit casting (needed for proper C++
// when MI is involved). // casting when MI is involved).
if (this_.try_implicit_casts(src, convert)) { if (this_.try_implicit_casts(src, convert)) {
return true; return true;
} }
@ -253,32 +262,36 @@ public:
// Perform an implicit conversion // Perform an implicit conversion
if (convert) { if (convert) {
for (auto &converter : typeinfo->implicit_conversions) { for (const auto &converter : typeinfo->implicit_conversions) {
auto temp = reinterpret_steal<object>(converter(src.ptr(), typeinfo->type)); auto temp = reinterpret_steal<object>(converter(src.ptr(), typeinfo->type));
if (load_impl<ThisT>(temp, false)) { if (load_impl<ThisT>(temp, false)) {
loader_life_support::add_patient(temp); loader_life_support::add_patient(temp);
return true; return true;
} }
} }
if (this_.try_direct_conversions(src)) if (this_.try_direct_conversions(src)) {
return true; return true;
} }
}
// Failed to match local typeinfo. Try again with global. // Failed to match local typeinfo. Try again with global.
if (typeinfo->module_local) { if (typeinfo->module_local) {
if (auto gtype = get_global_type_info(*typeinfo->cpptype)) { if (auto *gtype = get_global_type_info(*typeinfo->cpptype)) {
typeinfo = gtype; typeinfo = gtype;
return load(src, false); return load(src, false);
} }
} }
// Global typeinfo has precedence over foreign module_local // Global typeinfo has precedence over foreign module_local
if (try_load_foreign_module_local(src)) if (try_load_foreign_module_local(src)) {
return true; return true;
}
if (src.is_none()) { if (src.is_none()) {
// Defer accepting None to other overloads (if we aren't in convert mode): // Defer accepting None to other overloads (if we aren't in convert mode):
if (!convert) return false; if (!convert) {
return false;
}
loaded_v_h = value_and_holder(); loaded_v_h = value_and_holder();
return true; return true;
} }
@ -291,7 +304,7 @@ public:
void *unowned_void_ptr_from_direct_conversion = nullptr; void *unowned_void_ptr_from_direct_conversion = nullptr;
void *unowned_void_ptr_from_void_ptr_capsule = nullptr; void *unowned_void_ptr_from_void_ptr_capsule = nullptr;
const std::type_info *loaded_v_h_cpptype = nullptr; const std::type_info *loaded_v_h_cpptype = nullptr;
std::vector<void *(*)(void *)> implicit_casts; std::vector<void *(*) (void *)> implicit_casts;
value_and_holder loaded_v_h; value_and_holder loaded_v_h;
bool reinterpret_cast_deemed_ok = false; bool reinterpret_cast_deemed_ok = false;
// Magic number intentionally hard-coded, to guard against class_ holder mixups. // Magic number intentionally hard-coded, to guard against class_ holder mixups.
@ -326,8 +339,9 @@ struct smart_holder_type_caster_class_hooks : smart_holder_type_caster_base_tag
const std::enable_shared_from_this<SomeBaseOfWrappedType> *) { const std::enable_shared_from_this<SomeBaseOfWrappedType> *) {
auto shd_ptr = std::dynamic_pointer_cast<WrappedType>( auto shd_ptr = std::dynamic_pointer_cast<WrappedType>(
detail::try_get_shared_from_this(value_ptr_w_t)); detail::try_get_shared_from_this(value_ptr_w_t));
if (!shd_ptr) if (!shd_ptr) {
return false; return false;
}
// Note: inst->owned ignored. // Note: inst->owned ignored.
new (uninitialized_location) holder_type(holder_type::from_shared_ptr(shd_ptr)); new (uninitialized_location) holder_type(holder_type::from_shared_ptr(shd_ptr));
return true; return true;
@ -337,20 +351,20 @@ struct smart_holder_type_caster_class_hooks : smart_holder_type_caster_base_tag
static void init_instance_for_type(detail::instance *inst, const void *holder_const_void_ptr) { static void init_instance_for_type(detail::instance *inst, const void *holder_const_void_ptr) {
// Need for const_cast is a consequence of the type_info::init_instance type: // Need for const_cast is a consequence of the type_info::init_instance type:
// void (*init_instance)(instance *, const void *); // void (*init_instance)(instance *, const void *);
auto holder_void_ptr = const_cast<void *>(holder_const_void_ptr); auto *holder_void_ptr = const_cast<void *>(holder_const_void_ptr);
auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(WrappedType))); auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(WrappedType)));
if (!v_h.instance_registered()) { if (!v_h.instance_registered()) {
register_instance(inst, v_h.value_ptr(), v_h.type); register_instance(inst, v_h.value_ptr(), v_h.type);
v_h.set_instance_registered(); v_h.set_instance_registered();
} }
auto uninitialized_location = std::addressof(v_h.holder<holder_type>()); auto *uninitialized_location = std::addressof(v_h.holder<holder_type>());
auto value_ptr_w_t = v_h.value_ptr<WrappedType>(); auto *value_ptr_w_t = v_h.value_ptr<WrappedType>();
bool pointee_depends_on_holder_owner bool pointee_depends_on_holder_owner
= dynamic_raw_ptr_cast_if_possible<AliasType>(value_ptr_w_t) != nullptr; = dynamic_raw_ptr_cast_if_possible<AliasType>(value_ptr_w_t) != nullptr;
if (holder_void_ptr) { if (holder_void_ptr) {
// Note: inst->owned ignored. // Note: inst->owned ignored.
auto holder_ptr = static_cast<holder_type *>(holder_void_ptr); auto *holder_ptr = static_cast<holder_type *>(holder_void_ptr);
new (uninitialized_location) holder_type(std::move(*holder_ptr)); new (uninitialized_location) holder_type(std::move(*holder_ptr));
} else if (!try_initialization_using_shared_from_this( } else if (!try_initialization_using_shared_from_this(
uninitialized_location, value_ptr_w_t, value_ptr_w_t)) { uninitialized_location, value_ptr_w_t, value_ptr_w_t)) {
@ -399,8 +413,9 @@ struct smart_holder_type_caster_load {
bool load(handle src, bool convert) { bool load(handle src, bool convert) {
static_assert(type_uses_smart_holder_type_caster<T>::value, "Internal consistency error."); static_assert(type_uses_smart_holder_type_caster<T>::value, "Internal consistency error.");
load_impl = modified_type_caster_generic_load_impl(typeid(T)); load_impl = modified_type_caster_generic_load_impl(typeid(T));
if (!load_impl.load(src, convert)) if (!load_impl.load(src, convert)) {
return false; return false;
}
return true; return true;
} }
@ -413,18 +428,21 @@ struct smart_holder_type_caster_load {
if (have_holder()) { if (have_holder()) {
throw_if_uninitialized_or_disowned_holder(); throw_if_uninitialized_or_disowned_holder();
void_ptr = holder().template as_raw_ptr_unowned<void>(); void_ptr = holder().template as_raw_ptr_unowned<void>();
} else if (load_impl.loaded_v_h.vh != nullptr) } else if (load_impl.loaded_v_h.vh != nullptr) {
void_ptr = load_impl.loaded_v_h.value_ptr(); void_ptr = load_impl.loaded_v_h.value_ptr();
if (void_ptr == nullptr) }
if (void_ptr == nullptr) {
return nullptr; return nullptr;
} }
}
return convert_type(void_ptr); return convert_type(void_ptr);
} }
T &loaded_as_lvalue_ref() const { T &loaded_as_lvalue_ref() const {
T *raw_ptr = loaded_as_raw_ptr_unowned(); T *raw_ptr = loaded_as_raw_ptr_unowned();
if (raw_ptr == nullptr) if (raw_ptr == nullptr) {
throw reference_cast_error(); throw reference_cast_error();
}
return *raw_ptr; return *raw_ptr;
} }
@ -433,32 +451,35 @@ struct smart_holder_type_caster_load {
throw cast_error("Unowned pointer from a void pointer capsule cannot be converted to a" throw cast_error("Unowned pointer from a void pointer capsule cannot be converted to a"
" std::shared_ptr."); " std::shared_ptr.");
} }
if (load_impl.unowned_void_ptr_from_direct_conversion != nullptr) if (load_impl.unowned_void_ptr_from_direct_conversion != nullptr) {
throw cast_error("Unowned pointer from direct conversion cannot be converted to a" throw cast_error("Unowned pointer from direct conversion cannot be converted to a"
" std::shared_ptr."); " std::shared_ptr.");
if (!have_holder()) }
if (!have_holder()) {
return nullptr; return nullptr;
}
throw_if_uninitialized_or_disowned_holder(); throw_if_uninitialized_or_disowned_holder();
holder_type &hld = holder(); holder_type &hld = holder();
hld.ensure_is_not_disowned("loaded_as_shared_ptr"); hld.ensure_is_not_disowned("loaded_as_shared_ptr");
if (hld.vptr_is_using_noop_deleter) { if (hld.vptr_is_using_noop_deleter) {
throw std::runtime_error("Non-owning holder (loaded_as_shared_ptr)."); throw std::runtime_error("Non-owning holder (loaded_as_shared_ptr).");
} }
auto void_raw_ptr = hld.template as_raw_ptr_unowned<void>(); auto *void_raw_ptr = hld.template as_raw_ptr_unowned<void>();
auto type_raw_ptr = convert_type(void_raw_ptr); auto *type_raw_ptr = convert_type(void_raw_ptr);
if (hld.pointee_depends_on_holder_owner) { if (hld.pointee_depends_on_holder_owner) {
auto vptr_gd_ptr = std::get_deleter<pybindit::memory::guarded_delete>(hld.vptr); auto *vptr_gd_ptr = std::get_deleter<pybindit::memory::guarded_delete>(hld.vptr);
if (vptr_gd_ptr != nullptr) { if (vptr_gd_ptr != nullptr) {
std::shared_ptr<void> released_ptr = vptr_gd_ptr->released_ptr.lock(); std::shared_ptr<void> released_ptr = vptr_gd_ptr->released_ptr.lock();
if (released_ptr) if (released_ptr) {
return std::shared_ptr<T>(released_ptr, type_raw_ptr); return std::shared_ptr<T>(released_ptr, type_raw_ptr);
}
std::shared_ptr<T> to_be_released( std::shared_ptr<T> to_be_released(
type_raw_ptr, type_raw_ptr,
shared_ptr_trampoline_self_life_support(load_impl.loaded_v_h.inst)); shared_ptr_trampoline_self_life_support(load_impl.loaded_v_h.inst));
vptr_gd_ptr->released_ptr = to_be_released; vptr_gd_ptr->released_ptr = to_be_released;
return to_be_released; return to_be_released;
} }
auto sptsls_ptr = std::get_deleter<shared_ptr_trampoline_self_life_support>(hld.vptr); auto *sptsls_ptr = std::get_deleter<shared_ptr_trampoline_self_life_support>(hld.vptr);
if (sptsls_ptr != nullptr) { if (sptsls_ptr != nullptr) {
// This code is reachable only if there are multiple registered_instances for the // This code is reachable only if there are multiple registered_instances for the
// same pointee. // same pointee.
@ -491,11 +512,13 @@ struct smart_holder_type_caster_load {
throw cast_error("Unowned pointer from a void pointer capsule cannot be converted to a" throw cast_error("Unowned pointer from a void pointer capsule cannot be converted to a"
" std::unique_ptr."); " std::unique_ptr.");
} }
if (load_impl.unowned_void_ptr_from_direct_conversion != nullptr) if (load_impl.unowned_void_ptr_from_direct_conversion != nullptr) {
throw cast_error("Unowned pointer from direct conversion cannot be converted to a" throw cast_error("Unowned pointer from direct conversion cannot be converted to a"
" std::unique_ptr."); " std::unique_ptr.");
if (!have_holder()) }
if (!have_holder()) {
return nullptr; return nullptr;
}
throw_if_uninitialized_or_disowned_holder(); throw_if_uninitialized_or_disowned_holder();
throw_if_instance_is_currently_owned_by_shared_ptr(); throw_if_instance_is_currently_owned_by_shared_ptr();
holder().ensure_is_not_disowned(context); holder().ensure_is_not_disowned(context);
@ -572,7 +595,7 @@ private:
T *convert_type(void *void_ptr) const { T *convert_type(void *void_ptr) const {
if (void_ptr != nullptr && load_impl.loaded_v_h_cpptype != nullptr if (void_ptr != nullptr && load_impl.loaded_v_h_cpptype != nullptr
&& !load_impl.reinterpret_cast_deemed_ok && !load_impl.implicit_casts.empty()) { && !load_impl.reinterpret_cast_deemed_ok && !load_impl.implicit_casts.empty()) {
for (auto implicit_cast: load_impl.implicit_casts) { for (auto implicit_cast : load_impl.implicit_casts) {
void_ptr = implicit_cast(void_ptr); void_ptr = implicit_cast(void_ptr);
} }
} }
@ -603,8 +626,10 @@ struct smart_holder_type_caster : smart_holder_type_caster_load<T>,
static handle cast(T const &src, return_value_policy policy, handle parent) { static handle cast(T const &src, return_value_policy policy, handle parent) {
// type_caster_base BEGIN // type_caster_base BEGIN
if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference) if (policy == return_value_policy::automatic
|| policy == return_value_policy::automatic_reference) {
policy = return_value_policy::copy; policy = return_value_policy::copy;
}
return cast(&src, policy, parent); return cast(&src, policy, parent);
// type_caster_base END // type_caster_base END
} }
@ -660,18 +685,21 @@ struct smart_holder_type_caster : smart_holder_type_caster_load<T>,
void *(*copy_constructor)(const void *), void *(*copy_constructor)(const void *),
void *(*move_constructor)(const void *), void *(*move_constructor)(const void *),
const void *existing_holder = nullptr) { const void *existing_holder = nullptr) {
if (!tinfo) // no type info: error will be set already if (!tinfo) { // no type info: error will be set already
return handle(); return handle();
}
void *src = const_cast<void *>(_src); void *src = const_cast<void *>(_src);
if (src == nullptr) if (src == nullptr) {
return none().release(); return none().release();
}
if (handle existing_inst = find_registered_python_instance(src, tinfo)) if (handle existing_inst = find_registered_python_instance(src, tinfo)) {
return existing_inst; return existing_inst;
}
auto inst = reinterpret_steal<object>(make_new_instance(tinfo->type)); auto inst = reinterpret_steal<object>(make_new_instance(tinfo->type));
auto wrapper = reinterpret_cast<instance *>(inst.ptr()); auto *wrapper = reinterpret_cast<instance *>(inst.ptr());
wrapper->owned = false; wrapper->owned = false;
void *&valueptr = values_and_holders(wrapper).begin()->value_ptr(); void *&valueptr = values_and_holders(wrapper).begin()->value_ptr();
@ -689,9 +717,9 @@ struct smart_holder_type_caster : smart_holder_type_caster_load<T>,
break; break;
case return_value_policy::copy: case return_value_policy::copy:
if (copy_constructor) if (copy_constructor) {
valueptr = copy_constructor(src); valueptr = copy_constructor(src);
else { } else {
#if defined(NDEBUG) #if defined(NDEBUG)
throw cast_error("return_value_policy = copy, but type is " throw cast_error("return_value_policy = copy, but type is "
"non-copyable! (compile in debug mode for details)"); "non-copyable! (compile in debug mode for details)");
@ -706,11 +734,11 @@ struct smart_holder_type_caster : smart_holder_type_caster_load<T>,
break; break;
case return_value_policy::move: case return_value_policy::move:
if (move_constructor) if (move_constructor) {
valueptr = move_constructor(src); valueptr = move_constructor(src);
else if (copy_constructor) } else if (copy_constructor) {
valueptr = copy_constructor(src); valueptr = copy_constructor(src);
else { } else {
#if defined(NDEBUG) #if defined(NDEBUG)
throw cast_error("return_value_policy = move, but type is neither " throw cast_error("return_value_policy = move, but type is neither "
"movable nor copyable! " "movable nor copyable! "
@ -761,20 +789,23 @@ struct smart_holder_type_caster<std::shared_ptr<T>> : smart_holder_type_caster_l
case return_value_policy::reference_internal: case return_value_policy::reference_internal:
break; break;
} }
if (!src) if (!src) {
return none().release(); return none().release();
}
auto src_raw_ptr = src.get(); auto src_raw_ptr = src.get();
auto st = type_caster_base<T>::src_and_type(src_raw_ptr); auto st = type_caster_base<T>::src_and_type(src_raw_ptr);
if (st.second == nullptr) if (st.second == nullptr) {
return handle(); // no type info: error will be set already return handle(); // no type info: error will be set already
}
void *src_raw_void_ptr = static_cast<void *>(src_raw_ptr); void *src_raw_void_ptr = static_cast<void *>(src_raw_ptr);
const detail::type_info *tinfo = st.second; const detail::type_info *tinfo = st.second;
if (handle existing_inst = find_registered_python_instance(src_raw_void_ptr, tinfo)) if (handle existing_inst = find_registered_python_instance(src_raw_void_ptr, tinfo)) {
// SMART_HOLDER_WIP: MISSING: Enforcement of consistency with existing smart_holder. // SMART_HOLDER_WIP: MISSING: Enforcement of consistency with existing smart_holder.
// SMART_HOLDER_WIP: MISSING: keep_alive. // SMART_HOLDER_WIP: MISSING: keep_alive.
return existing_inst; return existing_inst;
}
auto inst = reinterpret_steal<object>(make_new_instance(tinfo->type)); auto inst = reinterpret_steal<object>(make_new_instance(tinfo->type));
auto *inst_raw_ptr = reinterpret_cast<instance *>(inst.ptr()); auto *inst_raw_ptr = reinterpret_cast<instance *>(inst.ptr());
@ -785,8 +816,9 @@ struct smart_holder_type_caster<std::shared_ptr<T>> : smart_holder_type_caster_l
auto smhldr = pybindit::memory::smart_holder::from_shared_ptr(src); auto smhldr = pybindit::memory::smart_holder::from_shared_ptr(src);
tinfo->init_instance(inst_raw_ptr, static_cast<const void *>(&smhldr)); tinfo->init_instance(inst_raw_ptr, static_cast<const void *>(&smhldr));
if (policy == return_value_policy::reference_internal) if (policy == return_value_policy::reference_internal) {
keep_alive_impl(inst, parent); keep_alive_impl(inst, parent);
}
return inst.release(); return inst.release();
} }
@ -830,13 +862,15 @@ struct smart_holder_type_caster<std::unique_ptr<T, D>> : smart_holder_type_caste
// SMART_HOLDER_WIP: IMPROVABLE: Error message. // SMART_HOLDER_WIP: IMPROVABLE: Error message.
throw cast_error("Invalid return_value_policy for unique_ptr."); throw cast_error("Invalid return_value_policy for unique_ptr.");
} }
if (!src) if (!src) {
return none().release(); return none().release();
}
auto src_raw_ptr = src.get(); auto src_raw_ptr = src.get();
auto st = type_caster_base<T>::src_and_type(src_raw_ptr); auto st = type_caster_base<T>::src_and_type(src_raw_ptr);
if (st.second == nullptr) if (st.second == nullptr) {
return handle(); // no type info: error will be set already return handle(); // no type info: error will be set already
}
void *src_raw_void_ptr = static_cast<void *>(src_raw_ptr); void *src_raw_void_ptr = static_cast<void *>(src_raw_ptr);
const detail::type_info *tinfo = st.second; const detail::type_info *tinfo = st.second;
@ -872,19 +906,23 @@ struct smart_holder_type_caster<std::unique_ptr<T, D>> : smart_holder_type_caste
/*void_cast_raw_ptr*/ false); /*void_cast_raw_ptr*/ false);
tinfo->init_instance(inst_raw_ptr, static_cast<const void *>(&smhldr)); tinfo->init_instance(inst_raw_ptr, static_cast<const void *>(&smhldr));
if (policy == return_value_policy::reference_internal) if (policy == return_value_policy::reference_internal) {
keep_alive_impl(inst, parent); keep_alive_impl(inst, parent);
}
return inst.release(); return inst.release();
} }
static handle static handle
cast(const std::unique_ptr<T, D> &src, return_value_policy policy, handle parent) { cast(const std::unique_ptr<T, D> &src, return_value_policy policy, handle parent) {
if (!src) if (!src) {
return none().release(); return none().release();
if (policy == return_value_policy::automatic) }
if (policy == return_value_policy::automatic) {
policy = return_value_policy::reference_internal; policy = return_value_policy::reference_internal;
if (policy != return_value_policy::reference_internal) }
if (policy != return_value_policy::reference_internal) {
throw cast_error("Invalid return_value_policy for unique_ptr&"); throw cast_error("Invalid return_value_policy for unique_ptr&");
}
return smart_holder_type_caster<T>::cast(src.get(), policy, parent); return smart_holder_type_caster<T>::cast(src.get(), policy, parent);
} }

View File

@ -4,9 +4,9 @@
#pragma once #pragma once
#include "pybind11.h"
#include "detail/common.h" #include "detail/common.h"
#include "detail/smart_holder_type_casters.h" #include "detail/smart_holder_type_casters.h"
#include "pybind11.h"
#undef PYBIND11_SH_AVL // Undoing #define in pybind11.h #undef PYBIND11_SH_AVL // Undoing #define in pybind11.h

View File

@ -1,7 +1,7 @@
#include "pybind11_tests.h"
#include <pybind11/smart_holder.h> #include <pybind11/smart_holder.h>
#include "pybind11_tests.h"
#include <memory> #include <memory>
#include <string> #include <string>
#include <vector> #include <vector>

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Importing re before pytest after observing a PyPy CI flake when importing pytest first. # Importing re before pytest after observing a PyPy CI flake when importing pytest first.
import re import re

View File

@ -1,7 +1,7 @@
#include "pybind11_tests.h"
#include <pybind11/smart_holder.h> #include <pybind11/smart_holder.h>
#include "pybind11_tests.h"
#include <memory> #include <memory>
namespace pybind11_tests { namespace pybind11_tests {

View File

@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import print_function
import pytest import pytest
from pybind11_tests import class_sh_disowning as m from pybind11_tests import class_sh_disowning as m

View File

@ -1,7 +1,7 @@
#include "pybind11_tests.h"
#include <pybind11/smart_holder.h> #include <pybind11/smart_holder.h>
#include "pybind11_tests.h"
#include <memory> #include <memory>
namespace pybind11_tests { namespace pybind11_tests {

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import pytest import pytest
import env # noqa: F401 import env # noqa: F401
@ -77,7 +76,7 @@ class MI1(m.Base1, m.Base2):
m.Base2.__init__(self, j) m.Base2.__init__(self, j)
class B1(object): class B1:
def v(self): def v(self):
return 1 return 1
@ -119,7 +118,7 @@ class B2(B1):
return 2 return 2
class B3(object): class B3:
def v(self): def v(self):
return 3 return 3

View File

@ -1,7 +1,7 @@
#include "pybind11_tests.h"
#include <pybind11/smart_holder.h> #include <pybind11/smart_holder.h>
#include "pybind11_tests.h"
#include <memory> #include <memory>
#include <string> #include <string>

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import pytest import pytest
from pybind11_tests import class_sh_factory_constructors as m from pybind11_tests import class_sh_factory_constructors as m

View File

@ -1,7 +1,7 @@
#include "pybind11_tests.h"
#include <pybind11/smart_holder.h> #include <pybind11/smart_holder.h>
#include "pybind11_tests.h"
#include <memory> #include <memory>
namespace pybind11_tests { namespace pybind11_tests {

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
from pybind11_tests import class_sh_inheritance as m from pybind11_tests import class_sh_inheritance as m

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import class_sh_module_local_0 as m0 import class_sh_module_local_0 as m0
import class_sh_module_local_1 as m1 import class_sh_module_local_1 as m1
import class_sh_module_local_2 as m2 import class_sh_module_local_2 as m2

View File

@ -1,7 +1,7 @@
#include "pybind11_tests.h"
#include <pybind11/smart_holder.h> #include <pybind11/smart_holder.h>
#include "pybind11_tests.h"
#include <memory> #include <memory>
#include <string> #include <string>
#include <vector> #include <vector>

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
from pybind11_tests import class_sh_shared_ptr_copy_move as m from pybind11_tests import class_sh_shared_ptr_copy_move as m
@ -25,8 +23,8 @@ def test_smhld_move():
def _check_property(foo_typ, prop_typ, policy): def _check_property(foo_typ, prop_typ, policy):
o = m.Outer() o = m.Outer()
name = "{}_{}_{}".format(foo_typ, prop_typ, policy) name = f"{foo_typ}_{prop_typ}_{policy}"
history = "Foo{}_Outer".format(foo_typ) history = f"Foo{foo_typ}_Outer"
f = getattr(o, name) f = getattr(o, name)
assert f.get_history() == history assert f.get_history() == history
# and try again to check that o did not get changed # and try again to check that o did not get changed

View File

@ -1,7 +1,7 @@
#include "pybind11_tests.h"
#include <pybind11/smart_holder.h> #include <pybind11/smart_holder.h>
#include "pybind11_tests.h"
#include <memory> #include <memory>
namespace pybind11_tests { namespace pybind11_tests {

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import pytest import pytest
from pybind11_tests import class_sh_trampoline_basic as m from pybind11_tests import class_sh_trampoline_basic as m
@ -6,7 +5,7 @@ from pybind11_tests import class_sh_trampoline_basic as m
class PyDrvd0(m.Abase0): class PyDrvd0(m.Abase0):
def __init__(self, val): def __init__(self, val):
super(PyDrvd0, self).__init__(val) super().__init__(val)
def Add(self, other_val): # noqa: N802 def Add(self, other_val): # noqa: N802
return self.Get() * 100 + other_val return self.Get() * 100 + other_val
@ -14,7 +13,7 @@ class PyDrvd0(m.Abase0):
class PyDrvd1(m.Abase1): class PyDrvd1(m.Abase1):
def __init__(self, val): def __init__(self, val):
super(PyDrvd1, self).__init__(val) super().__init__(val)
def Add(self, other_val): # noqa: N802 def Add(self, other_val): # noqa: N802
return self.Get() * 200 + other_val return self.Get() * 200 + other_val

View File

@ -54,7 +54,7 @@ TEST_SUBMODULE(class_sh_trampoline_self_life_support, m) {
py::object o2 = py::none(); py::object o2 = py::none();
// This is very unusual, but needed to directly exercise the trampoline_self_life_support // This is very unusual, but needed to directly exercise the trampoline_self_life_support
// CpCtor, MvCtor, operator= lvalue, operator= rvalue. // CpCtor, MvCtor, operator= lvalue, operator= rvalue.
auto obj_trampoline = dynamic_cast<Big5Trampoline *>(obj.get()); auto *obj_trampoline = dynamic_cast<Big5Trampoline *>(obj.get());
if (obj_trampoline != nullptr) { if (obj_trampoline != nullptr) {
switch (action_id) { switch (action_id) {
case 0: { // CpCtor case 0: { // CpCtor

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import pytest import pytest
import pybind11_tests.class_sh_trampoline_self_life_support as m import pybind11_tests.class_sh_trampoline_self_life_support as m

View File

@ -57,13 +57,15 @@ struct SftSharedPtrStash {
stash.push_back(sft); stash.push_back(sft);
} }
std::string history(unsigned i) { std::string history(unsigned i) {
if (i < stash.size()) if (i < stash.size()) {
return stash[i]->history; return stash[i]->history;
}
return "OutOfRange"; return "OutOfRange";
} }
long use_count(unsigned i) { long use_count(unsigned i) {
if (i < stash.size()) if (i < stash.size()) {
return stash[i].use_count(); return stash[i].use_count();
}
return -1; return -1;
} }
}; };

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import sys import sys
import weakref import weakref
@ -220,7 +219,7 @@ WORKAROUND_ENABLING_ROLLBACK_OF_PR3068 = env.LINUX and sys.version_info == (3, 9
def test_std_make_shared_factory(): def test_std_make_shared_factory():
class PySftMakeShared(m.Sft): class PySftMakeShared(m.Sft):
def __init__(self, history): def __init__(self, history):
super(PySftMakeShared, self).__init__(history, 0) super().__init__(history, 0)
obj = PySftMakeShared("PySftMakeShared") obj = PySftMakeShared("PySftMakeShared")
assert obj.history == "PySftMakeShared" assert obj.history == "PySftMakeShared"

View File

@ -2,11 +2,11 @@
// All rights reserved. Use of this source code is governed by a // All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file. // BSD-style license that can be found in the LICENSE file.
#include <utility>
#include "pybind11/smart_holder.h" #include "pybind11/smart_holder.h"
#include "pybind11_tests.h" #include "pybind11_tests.h"
#include <utility>
namespace { namespace {
// For testing whether a python subclass of a C++ object dies when the // For testing whether a python subclass of a C++ object dies when the
@ -17,7 +17,7 @@ struct SpBase {
// returns true if there's an associated python instance // returns true if there's an associated python instance
bool has_python_instance() { bool has_python_instance() {
auto tinfo = py::detail::get_type_info(typeid(SpBase)); auto *tinfo = py::detail::get_type_info(typeid(SpBase));
return (bool) py::detail::get_object_handle(this, tinfo); return (bool) py::detail::get_object_handle(this, tinfo);
} }

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import pytest import pytest
import pybind11_tests.class_sh_trampoline_shared_ptr_cpp_arg as m import pybind11_tests.class_sh_trampoline_shared_ptr_cpp_arg as m
@ -136,7 +135,7 @@ def test_infinite():
def test_std_make_shared_factory(): def test_std_make_shared_factory():
class PyChild(m.SpBase): class PyChild(m.SpBase):
def __init__(self): def __init__(self):
super(PyChild, self).__init__(0) super().__init__(0)
obj = PyChild() obj = PyChild()
while True: while True:

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import pybind11_tests.class_sh_trampoline_unique_ptr as m import pybind11_tests.class_sh_trampoline_unique_ptr as m

View File

@ -1,7 +1,7 @@
#include "pybind11_tests.h"
#include <pybind11/smart_holder.h> #include <pybind11/smart_holder.h>
#include "pybind11_tests.h"
#include <memory> #include <memory>
namespace pybind11_tests { namespace pybind11_tests {

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import pytest import pytest
from pybind11_tests import class_sh_unique_ptr_member as m from pybind11_tests import class_sh_unique_ptr_member as m

View File

@ -1,7 +1,7 @@
#include "pybind11_tests.h"
#include <pybind11/smart_holder.h> #include <pybind11/smart_holder.h>
#include "pybind11_tests.h"
#include <memory> #include <memory>
namespace pybind11_tests { namespace pybind11_tests {

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import pytest import pytest
from pybind11_tests import class_sh_virtual_py_cpp_mix as m from pybind11_tests import class_sh_virtual_py_cpp_mix as m

View File

@ -1,7 +1,7 @@
#include "pybind11_tests.h"
#include <pybind11/smart_holder.h> #include <pybind11/smart_holder.h>
#include "pybind11_tests.h"
#include <memory> #include <memory>
namespace pybind11_tests { namespace pybind11_tests {
@ -27,67 +27,53 @@ struct HelperBase {
virtual int get() const { return 100; } virtual int get() const { return 100; }
}; };
struct Valid: public HelperBase { struct Valid : public HelperBase {
int get() const override { return 101; } int get() const override { return 101; }
PyObject* as_pybind11_tests_class_sh_void_ptr_capsule_Valid() { PyObject *as_pybind11_tests_class_sh_void_ptr_capsule_Valid() {
void* vptr = dynamic_cast<void*>(this); void *vptr = dynamic_cast<void *>(this);
capsule_generated = true; capsule_generated = true;
// We assume vptr out lives the capsule, so we use nullptr for the // We assume vptr out lives the capsule, so we use nullptr for the
// destructor. // destructor.
return PyCapsule_New( return PyCapsule_New(vptr, "::pybind11_tests::class_sh_void_ptr_capsule::Valid", nullptr);
vptr, "::pybind11_tests::class_sh_void_ptr_capsule::Valid",
nullptr);
} }
}; };
struct NoConversion: public HelperBase { struct NoConversion : public HelperBase {
int get() const override { return 102; } int get() const override { return 102; }
}; };
struct NoCapsuleReturned: public HelperBase { struct NoCapsuleReturned : public HelperBase {
int get() const override { return 103; } int get() const override { return 103; }
PyObject* as_pybind11_tests_class_sh_void_ptr_capsule_NoCapsuleReturned() { PyObject *as_pybind11_tests_class_sh_void_ptr_capsule_NoCapsuleReturned() {
capsule_generated = true; capsule_generated = true;
Py_XINCREF(Py_None); Py_XINCREF(Py_None);
return Py_None; return Py_None;
} }
}; };
struct AsAnotherObject: public HelperBase { struct AsAnotherObject : public HelperBase {
int get() const override { return 104; } int get() const override { return 104; }
PyObject* as_pybind11_tests_class_sh_void_ptr_capsule_Valid() { PyObject *as_pybind11_tests_class_sh_void_ptr_capsule_Valid() {
void* vptr = dynamic_cast<void*>(this); void *vptr = dynamic_cast<void *>(this);
capsule_generated = true; capsule_generated = true;
// We assume vptr out lives the capsule, so we use nullptr for the // We assume vptr out lives the capsule, so we use nullptr for the
// destructor. // destructor.
return PyCapsule_New( return PyCapsule_New(vptr, "::pybind11_tests::class_sh_void_ptr_capsule::Valid", nullptr);
vptr, "::pybind11_tests::class_sh_void_ptr_capsule::Valid",
nullptr);
} }
}; };
int get_from_valid_capsule(const Valid* c) { int get_from_valid_capsule(const Valid *c) { return c->get(); }
return c->get();
}
int get_from_shared_ptr_valid_capsule(const std::shared_ptr<Valid> &c) { int get_from_shared_ptr_valid_capsule(const std::shared_ptr<Valid> &c) { return c->get(); }
return c->get();
}
int get_from_unique_ptr_valid_capsule(std::unique_ptr<Valid> c) { int get_from_unique_ptr_valid_capsule(std::unique_ptr<Valid> c) { return c->get(); }
return c->get();
}
int get_from_no_conversion_capsule(const NoConversion* c) { int get_from_no_conversion_capsule(const NoConversion *c) { return c->get(); }
return c->get();
}
int get_from_no_capsule_returned(const NoCapsuleReturned* c) { int get_from_no_capsule_returned(const NoCapsuleReturned *c) { return c->get(); }
return c->get();
}
} // namespace class_sh_void_ptr_capsule } // namespace class_sh_void_ptr_capsule
} // namespace pybind11_tests } // namespace pybind11_tests
@ -108,34 +94,32 @@ TEST_SUBMODULE(class_sh_void_ptr_capsule, m) {
py::classh<Valid, HelperBase>(m, "Valid") py::classh<Valid, HelperBase>(m, "Valid")
.def(py::init<>()) .def(py::init<>())
.def("as_pybind11_tests_class_sh_void_ptr_capsule_Valid", .def("as_pybind11_tests_class_sh_void_ptr_capsule_Valid", [](HelperBase *self) {
[](HelperBase* self) { auto *obj = dynamic_cast<Valid *>(self);
auto obj = dynamic_cast<Valid *>(self);
assert(obj != nullptr); assert(obj != nullptr);
PyObject* capsule = obj->as_pybind11_tests_class_sh_void_ptr_capsule_Valid(); PyObject *capsule = obj->as_pybind11_tests_class_sh_void_ptr_capsule_Valid();
return pybind11::reinterpret_steal<py::capsule>(capsule); return pybind11::reinterpret_steal<py::capsule>(capsule);
}); });
py::classh<NoConversion, HelperBase>(m, "NoConversion") py::classh<NoConversion, HelperBase>(m, "NoConversion").def(py::init<>());
.def(py::init<>());
py::classh<NoCapsuleReturned, HelperBase>(m, "NoCapsuleReturned") py::classh<NoCapsuleReturned, HelperBase>(m, "NoCapsuleReturned")
.def(py::init<>()) .def(py::init<>())
.def("as_pybind11_tests_class_sh_void_ptr_capsule_NoCapsuleReturned", .def("as_pybind11_tests_class_sh_void_ptr_capsule_NoCapsuleReturned",
[](HelperBase* self) { [](HelperBase *self) {
auto obj = dynamic_cast<NoCapsuleReturned *>(self); auto *obj = dynamic_cast<NoCapsuleReturned *>(self);
assert(obj != nullptr); assert(obj != nullptr);
PyObject* capsule = obj->as_pybind11_tests_class_sh_void_ptr_capsule_NoCapsuleReturned(); PyObject *capsule
= obj->as_pybind11_tests_class_sh_void_ptr_capsule_NoCapsuleReturned();
return pybind11::reinterpret_steal<py::capsule>(capsule); return pybind11::reinterpret_steal<py::capsule>(capsule);
}); });
py::classh<AsAnotherObject, HelperBase>(m, "AsAnotherObject") py::classh<AsAnotherObject, HelperBase>(m, "AsAnotherObject")
.def(py::init<>()) .def(py::init<>())
.def("as_pybind11_tests_class_sh_void_ptr_capsule_Valid", .def("as_pybind11_tests_class_sh_void_ptr_capsule_Valid", [](HelperBase *self) {
[](HelperBase* self) { auto *obj = dynamic_cast<AsAnotherObject *>(self);
auto obj = dynamic_cast<AsAnotherObject *>(self);
assert(obj != nullptr); assert(obj != nullptr);
PyObject* capsule = obj->as_pybind11_tests_class_sh_void_ptr_capsule_Valid(); PyObject *capsule = obj->as_pybind11_tests_class_sh_void_ptr_capsule_Valid();
return pybind11::reinterpret_steal<py::capsule>(capsule); return pybind11::reinterpret_steal<py::capsule>(capsule);
}); });

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import pytest import pytest
from pybind11_tests import class_sh_void_ptr_capsule as m from pybind11_tests import class_sh_void_ptr_capsule as m

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
from pybind11_tests import classh_mock as m from pybind11_tests import classh_mock as m

View File

@ -298,8 +298,11 @@ PYBIND11_TYPE_CASTER_BASE_HOLDER(SharedFromThisRef::B, std::shared_ptr<SharedFro
PYBIND11_TYPE_CASTER_BASE_HOLDER(SharedFromThisRef, std::unique_ptr<SharedFromThisRef>) PYBIND11_TYPE_CASTER_BASE_HOLDER(SharedFromThisRef, std::unique_ptr<SharedFromThisRef>)
PYBIND11_TYPE_CASTER_BASE_HOLDER(SharedFromThisVirt, std::shared_ptr<SharedFromThisVirt>) PYBIND11_TYPE_CASTER_BASE_HOLDER(SharedFromThisVirt, std::shared_ptr<SharedFromThisVirt>)
PYBIND11_TYPE_CASTER_BASE_HOLDER(C, custom_unique_ptr<C>) PYBIND11_TYPE_CASTER_BASE_HOLDER(C, custom_unique_ptr<C>)
PYBIND11_TYPE_CASTER_BASE_HOLDER(TypeForHolderWithAddressOf, shared_ptr_with_addressof_operator<TypeForHolderWithAddressOf>) PYBIND11_TYPE_CASTER_BASE_HOLDER(TypeForHolderWithAddressOf,
PYBIND11_TYPE_CASTER_BASE_HOLDER(TypeForMoveOnlyHolderWithAddressOf, unique_ptr_with_addressof_operator<TypeForMoveOnlyHolderWithAddressOf>) shared_ptr_with_addressof_operator<TypeForHolderWithAddressOf>)
PYBIND11_TYPE_CASTER_BASE_HOLDER(
TypeForMoveOnlyHolderWithAddressOf,
unique_ptr_with_addressof_operator<TypeForMoveOnlyHolderWithAddressOf>)
PYBIND11_TYPE_CASTER_BASE_HOLDER(HeldByDefaultHolder, std::unique_ptr<HeldByDefaultHolder>) PYBIND11_TYPE_CASTER_BASE_HOLDER(HeldByDefaultHolder, std::unique_ptr<HeldByDefaultHolder>)
PYBIND11_TYPE_CASTER_BASE_HOLDER(ElementBase, std::shared_ptr<ElementBase>) PYBIND11_TYPE_CASTER_BASE_HOLDER(ElementBase, std::shared_ptr<ElementBase>)
PYBIND11_TYPE_CASTER_BASE_HOLDER(ElementA, std::shared_ptr<ElementA>) PYBIND11_TYPE_CASTER_BASE_HOLDER(ElementA, std::shared_ptr<ElementA>)
@ -308,7 +311,8 @@ PYBIND11_TYPE_CASTER_BASE_HOLDER(ElementList, std::shared_ptr<ElementList>)
#ifdef PYBIND11_USE_SMART_HOLDER_AS_DEFAULT #ifdef PYBIND11_USE_SMART_HOLDER_AS_DEFAULT
// To prevent triggering a static_assert in the smart_holder code. // To prevent triggering a static_assert in the smart_holder code.
// This is a very special case, because the associated test exercises a holder mismatch. // This is a very special case, because the associated test exercises a holder mismatch.
namespace pybind11 { namespace detail { namespace pybind11 {
namespace detail {
template <> template <>
class type_caster<std::shared_ptr<HeldByDefaultHolder>> class type_caster<std::shared_ptr<HeldByDefaultHolder>>
: public copyable_holder_caster<HeldByDefaultHolder, std::shared_ptr<HeldByDefaultHolder>> {}; : public copyable_holder_caster<HeldByDefaultHolder, std::shared_ptr<HeldByDefaultHolder>> {};

View File

@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
"""Simple comparison of holder performances, relative to unique_ptr holder.""" """Simple comparison of holder performances, relative to unique_ptr holder."""
from __future__ import absolute_import, division, print_function
import collections import collections
import sys import sys
import time import time
@ -74,7 +72,7 @@ def run(args: List[str]) -> None:
for size_exponent in range( for size_exponent in range(
size_exponent_min, size_exponent_max + 1, size_exponent_step size_exponent_min, size_exponent_max + 1, size_exponent_step
): ):
data_size = 2 ** size_exponent data_size = 2**size_exponent
pflush(data_size, "data_size") pflush(data_size, "data_size")
ratios: Dict[str, List[float]] = collections.defaultdict(list) ratios: Dict[str, List[float]] = collections.defaultdict(list)
call_repetitions = None call_repetitions = None

View File

@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
"""Extract mean ratios from holder_comparison.py output.""" """Extract mean ratios from holder_comparison.py output."""
from __future__ import absolute_import, division, print_function
import sys import sys
from typing import List, Optional from typing import List, Optional