@@ -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+
163199if __name__ == '__main__' :
164200 unittest .main ()
0 commit comments