Skip to content

Commit 3b66075

Browse files
committed
missing implementation: casting const std::unique_ptr<T>&
This causes, for example, make_iterator to fail.
1 parent d6cf6df commit 3b66075

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

tests/test_sequences_and_iterators.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,4 +355,5 @@ TEST_SUBMODULE(sequences_and_iterators, m) {
355355
static std::vector<int> list = { 1, 2, 3 };
356356
m.def("make_iterator_1", []() { return py::make_iterator<py::return_value_policy::copy>(list); });
357357
m.def("make_iterator_2", []() { return py::make_iterator<py::return_value_policy::automatic>(list); });
358+
358359
}

tests/test_smart_ptr.cpp

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -462,4 +462,25 @@ TEST_SUBMODULE(smart_ptr, m) {
462462
list.append(py::cast(e));
463463
return list;
464464
});
465+
466+
// list of std::unique_ptr<T>
467+
struct IntType {
468+
IntType(int value) : value(value) {}
469+
int value;
470+
};
471+
using IntTypeHolder = std::unique_ptr<IntType>;
472+
struct IntTypeList : std::list<IntTypeHolder> {
473+
const IntTypeHolder& front() const { return std::list<IntTypeHolder>::front(); }
474+
};
475+
py::class_<IntType>(m, "IntType").def(py::init<int>()).def_readwrite("value", &IntType::value);
476+
py::class_<IntTypeList>(m, "IntTypeList")
477+
.def("front", &IntTypeList::front, py::return_value_policy::reference_internal)
478+
.def("__iter__", [](IntTypeList &c) { return py::make_iterator(c.begin(), c.end()); },
479+
py::keep_alive<0, 1>());
480+
m.def("make_int_type_list", [](py::object o) {
481+
IntTypeList l;
482+
for (auto item : o)
483+
l.emplace_back(IntTypeHolder(new IntType(py::cast<int>(item))));
484+
return l;
485+
});
465486
}

tests/test_smart_ptr.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,3 +316,9 @@ def test_shared_ptr_gc():
316316
pytest.gc_collect()
317317
for i, v in enumerate(el.get()):
318318
assert i == v.value()
319+
320+
321+
def test_iterator_for_list_of_holders():
322+
lst = m.make_int_type_list([1, 2, 3])
323+
assert lst.front().value == 1
324+
assert [obj.value for obj in lst] == [1, 2, 3]

0 commit comments

Comments
 (0)