Skip to content

Commit 7d2ae64

Browse files
committed
test: verify reference_internal policy for const-ref returns
Adds test_const_ref_return_policy that explicitly checks: - Methods returning const T& emit `-> const auto&` trailing return - Methods returning const T& emit `py::return_value_policy::reference_internal` - Methods returning by value (T, not T&) do NOT get the policy
1 parent 1de7f41 commit 7d2ae64

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

tests/test_pybind_wrapper.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,5 +160,41 @@ def test_enum(self):
160160
self.compare_and_diff('enum_pybind.cpp', output)
161161

162162

163+
def test_const_ref_return_policy(self):
164+
"""Test that methods returning const T& emit reference_internal policy.
165+
166+
Without this policy, pybind11 defaults to copying the returned reference.
167+
With the policy, the binding keeps the reference alive via the parent object.
168+
169+
Expected emitted code difference:
170+
Before: [](Cls* self, ...){return self->method(...);}, py::arg(...))
171+
After: [](Cls* self, ...) -> const auto&{return self->method(...);},
172+
py::return_value_policy::reference_internal, py::arg(...))
173+
"""
174+
source = osp.join(self.INTERFACE_DIR, 'class.i')
175+
output = self.wrap_content([source], 'class_py',
176+
self.PYTHON_ACTUAL_DIR)
177+
178+
with open(output, 'r') as f:
179+
content = f.read()
180+
181+
# const Vector& return_vector2 should have reference_internal
182+
self.assertIn('-> const auto&{return self->return_vector2', content)
183+
self.assertIn('py::return_value_policy::reference_internal', content)
184+
185+
# const Matrix& return_matrix2 should also have reference_internal
186+
self.assertIn('-> const auto&{return self->return_matrix2', content)
187+
188+
# Non-ref returns (e.g. return_vector1 which returns by value) should NOT
189+
lines = content.split('\n')
190+
for line in lines:
191+
if 'return_vector1' in line:
192+
self.assertNotIn('reference_internal', line)
193+
self.assertNotIn('-> const auto&', line)
194+
if 'return_matrix1' in line:
195+
self.assertNotIn('reference_internal', line)
196+
self.assertNotIn('-> const auto&', line)
197+
198+
163199
if __name__ == '__main__':
164200
unittest.main()

0 commit comments

Comments
 (0)