From 6277910abd119d80ec91318dd1b1920ee1e75ab6 Mon Sep 17 00:00:00 2001 From: "Ralf W. Grosse-Kunstleve" Date: Mon, 11 Jan 2021 22:04:18 -0800 Subject: [PATCH] Improved error messaging: Cannot disown nullptr (as_unique_ptr). --- include/pybind11/smart_holder_poc.h | 4 ++++ tests/core/smart_holder_poc_test.cpp | 7 +++++++ 2 files changed, 11 insertions(+) diff --git a/include/pybind11/smart_holder_poc.h b/include/pybind11/smart_holder_poc.h index f3374f103..8f7b62651 100644 --- a/include/pybind11/smart_holder_poc.h +++ b/include/pybind11/smart_holder_poc.h @@ -134,6 +134,10 @@ struct smart_holder { } void ensure_use_count_1(const char* context) const { + if (vptr.get() == nullptr) { + throw std::runtime_error(std::string("Cannot disown nullptr (") + + context + ")."); + } if (vptr.use_count() != 1) { throw std::runtime_error(std::string("Cannot disown use_count != 1 (") + context + ")."); diff --git a/tests/core/smart_holder_poc_test.cpp b/tests/core/smart_holder_poc_test.cpp index e696d9e53..dbd836b6f 100644 --- a/tests/core/smart_holder_poc_test.cpp +++ b/tests/core/smart_holder_poc_test.cpp @@ -317,3 +317,10 @@ TEST_CASE("error_disowned_holder", "[E]") { hld.as_unique_ptr(); REQUIRE_THROWS_WITH(hld.lvalue_ref(), "Disowned holder (lvalue_ref)."); } + +TEST_CASE("error_cannot_disown_nullptr", "[E]") { + auto hld = smart_holder::from_raw_ptr_take_ownership(new int(19)); + hld.as_unique_ptr(); + REQUIRE_THROWS_WITH(hld.as_unique_ptr(), + "Cannot disown nullptr (as_unique_ptr)."); +}