Skip to content

better test for const only smart ptr #5727

New issue

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

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

Already on GitHub? # to your account

Merged
merged 1 commit into from
Jun 14, 2025
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
23 changes: 18 additions & 5 deletions tests/test_smart_ptr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,20 @@ class MyObject5 { // managed by huge_unique_ptr
int value;
};

// test const_only_shared_ptr
class MyObject6 {
public:
static const_only_shared_ptr<MyObject6> createObject(std::string value) {
return const_only_shared_ptr<MyObject6>(new MyObject6(std::move(value)));
}

const std::string &value() const { return value_; }

private:
explicit MyObject6(std::string &&value) : value_{std::move(value)} {}
std::string value_;
};

// test_shared_ptr_and_references
struct SharedPtrRef {
struct A {
Expand Down Expand Up @@ -412,11 +426,6 @@ TEST_SUBMODULE(smart_ptr, m) {
m.def("print_myobject2_4",
[](const std::shared_ptr<MyObject2> *obj) { py::print((*obj)->toString()); });

m.def("make_myobject2_3",
[](int val) { return const_only_shared_ptr<MyObject2>(new MyObject2(val)); });
m.def("print_myobject2_5",
[](const const_only_shared_ptr<MyObject2> &obj) { py::print(obj.get()->toString()); });

py::class_<MyObject3, std::shared_ptr<MyObject3>>(m, "MyObject3").def(py::init<int>());
m.def("make_myobject3_1", []() { return new MyObject3(8); });
m.def("make_myobject3_2", []() { return std::make_shared<MyObject3>(9); });
Expand Down Expand Up @@ -459,6 +468,10 @@ TEST_SUBMODULE(smart_ptr, m) {
.def(py::init<int>())
.def_readwrite("value", &MyObject5::value);

py::class_<MyObject6, const_only_shared_ptr<MyObject6>>(m, "MyObject6")
.def(py::init([](const std::string &value) { return MyObject6::createObject(value); }))
.def_property_readonly("value", &MyObject6::value);

// test_shared_ptr_and_references
using A = SharedPtrRef::A;
py::class_<A, std::shared_ptr<A>>(m, "A");
Expand Down
8 changes: 3 additions & 5 deletions tests/test_smart_ptr.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,8 +352,6 @@ def test_move_only_holder_caster_shared_ptr_with_smart_holder_support_enabled():
)


def test_const_only_holder(capture):
o = m.make_myobject2_3(4)
with capture:
m.print_myobject2_5(o)
assert capture == "MyObject2[4]\n"
def test_const_only_holder():
o = m.MyObject6("my_data")
assert o.value == "my_data"
Loading