Fix memory leak with move assignment operator #366
Merged
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.
Closes #338
This is rather complicated, and is caught up in the fact that we currently double protect all writable r_vectors (oops), but this is the minimal fix for #338. More changes are coming to simplify things further.
Here's the basic idea of what was happening (glossing over double protect weirdness). Take this example:
Here are the protection counts:
+1 x
The constructor createsx
and protects it+1 <temp>
An rvalue (temporary) ofcpp11::writable::integers(1)
is created and protected+1 <temp>
WRONG! The move assignment operator is re-protecting the rvalue SEXP as it takes ownership of it rather than just taking the protect token from the rhs.-1 x
The move assignment operator releases oldx
rhs.protect_ = R_NilValue
so when rhs is destructed, it can't release anythingSo if you add that up you end with a
+2
count of items protected in the protection list when it should be+1
, and that was indeed what I was seeing in my new tests. The memory of the<temp>
value can never be released because the protection list always holds a reference to it.The solution is simple - we just move the
rhs.protect_
value intox
rather than generating our own. This was probably the intention the whole time anyways, since we were also doingrhs.protect_ = R_NilValue
at the end.