Default to rv_policy::move when binding in-place operators #803
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.
The idiomatic return type for
T::operator+=
in C++ isT&
, because the idiomatic return value is*this
. When bindingnb::self += nb::self
, or any other augmented-assignment operator, for a class that follows this convention, nanobind currently appliesrv_policy::automatic
to theT&
return value and makes a copy of the referencedT
. I think this is counter to users' expectations: a C++ type that defines these augmented assignment operators is mutable, so it should behave like mutable objects do in Python, and let+=
preserve object identity. The problem is demonstrated by the test in this PR, which fails on current master.Fix this issue by defaulting to
rv_policy::move
for the return value of augmented assignment operators. This will work as it does today if the operator returns by value, but be able to reuse the same Python object if the operator returns*this
by reference. Users can still override the default by passing an rvp as an additional argument to.def()
.Footnote: This issue suggests a potential wider problem when binding "generative methods" like
Foo& Foo::withBar(int bar) { myBar = bar; return *this; }
; using those in Python will make a copy too, becauserv_policy::copy
prevents reusing an existing pyobject on nanobind. (This is a difference from pybind and maybe should be mentioned in the porting section?) However, I don't think we can conclude that all methods returning reference-to-self-type return*this
; it's a much more robust assumption for augmented assignment operators.