Open kfsone opened 1 year ago
The std::exchange requires c++14, however, so you may want to just use
: data_(other.data_), owned_(other.owned_) { other.data_ = nullptr; other.owned_ = false; }
@kfsone Sure, it's not a pure move but we're copying a pointer which is instant? Why is this a problem?
Exactly that you are copying the pointer. If the object you are copying from is a temporary, it will be destroyed immediately after this method. The pointer you copied is now invalid.
std::move and std::forward are just casts, it's the operators that have to actually perform the movement.
Here's a demonstrative example, change the "MOVE_NOT_COPY" on the first line from 0 to 1 to see it operate without leaking/multi-deleting.
https://gcc.godbolt.org/z/PWxExbPx1
Note in particular where A#4 and A#7 are ~d relative to the end of scope.
Passing an rvalue reference to an object makes it an rvalue. The only reason that the language doesn't automatically delete named rvalues is so that you can reuse their storage, which in turn depends on them having good move operators.
{
A a1{};
A a2 = std::move(a1); // a1 is now dead and the compiler COULD dtor it here, but that would add extra requirements on dtors.
a1 = A{}; // create temporary, rvalue assign it to a1, dtor the temporary.
} // dtor a2, dtor a1
https://github.com/DaanDeMeyer/reproc/blob/08675b1b1f1317afa4c8b39fa3a180e7b7ec4ced/reproc%2B%2B/include/reproc%2B%2B/detail/array.hpp#L23-L30
The move-assignment operator is not actually moving but copying.
https://gcc.godbolt.org/z/az44M1577
Move should be implemented as swap or exchange:
https://gcc.godbolt.org/z/5fzrhaGvd