Passing reference arguments to trampoline methods #2915
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This is a set of new unit tests validating the correct passing of arguments from Python to C++ via trampoline methods,
i.e. Python-overridden virtual methods of C++ classes. While arguments are correctly passed by value or via pointer (copying vs. reference passing it as expected), there is one exception, namely (lvalue) reference arguments: These are actually copied.
The reason is that the (fixed) policy for this type of action is
automatic_reference
:pybind11/include/pybind11/pytypes.h
Lines 108 to 109 in 417067e
which resolves to
copy
for references:pybind11/include/pybind11/detail/type_caster_base.h
Lines 867 to 869 in 0c42250
However, being able to pass by reference is essential in this case to allow object modifications
performed in Python code to become visible in C++ as well.
The object passed to Python will be alive during the whole lifetime of the method call. Thus it should be safe to pass by reference always. Of course, the Python code shouldn't keep a global copy of the passed variable, because it might/will get invalidated later.