Skip to content

[smart_holder] Support loading unique_ptr<Derived> as unique_ptr<Base>. #4031

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion include/pybind11/detail/smart_holder_poc.h
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,9 @@ struct smart_holder {
+ ").");
}
ensure_vptr_is_using_builtin_delete(context);
} else if (!(*rtti_requested == *rtti_uqp_del)) {
} else if (!(*rtti_requested == *rtti_uqp_del)
&& !(vptr_is_using_builtin_delete
&& is_std_default_delete<T>(*rtti_requested))) {
throw std::invalid_argument(std::string("Incompatible unique_ptr deleter (") + context
+ ").");
}
Expand Down
28 changes: 28 additions & 0 deletions tests/pure_cpp/smart_holder_poc_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,15 @@ struct indestructible_int {
~indestructible_int() = default;
};

struct base {
virtual int get() { return 10; }
virtual ~base() = default;
};

struct derived : public base {
int get() override { return 100; }
};

} // namespace helpers

TEST_CASE("from_raw_ptr_unowned+as_raw_ptr_unowned", "[S]") {
Expand Down Expand Up @@ -227,6 +236,25 @@ TEST_CASE("from_unique_ptr+as_shared_ptr", "[S]") {
REQUIRE(*new_owner == 19);
}

TEST_CASE("from_unique_ptr_derived+as_unique_ptr_base", "[S]") {
std::unique_ptr<helpers::derived> orig_owner(new helpers::derived());
auto hld = smart_holder::from_unique_ptr(std::move(orig_owner));
REQUIRE(orig_owner.get() == nullptr);
std::unique_ptr<helpers::base> new_owner = hld.as_unique_ptr<helpers::base>();
REQUIRE(!hld.has_pointee());
REQUIRE(new_owner->get() == 100);
}

TEST_CASE("from_unique_ptr_derived+as_unique_ptr_base2", "[E]") {
std::unique_ptr<helpers::derived, helpers::functor_other_delete<helpers::derived>> orig_owner(
new helpers::derived());
auto hld = smart_holder::from_unique_ptr(std::move(orig_owner));
REQUIRE(orig_owner.get() == nullptr);
REQUIRE_THROWS_WITH(
(hld.as_unique_ptr<helpers::base, helpers::functor_builtin_delete<helpers::base>>()),
"Incompatible unique_ptr deleter (as_unique_ptr).");
}

TEST_CASE("from_unique_ptr_with_deleter+as_lvalue_ref", "[S]") {
std::unique_ptr<int, helpers::functor_builtin_delete<int>> orig_owner(new int(19));
auto hld = smart_holder::from_unique_ptr(std::move(orig_owner));
Expand Down