4 ms·
> The difference is that you don't have to write "std::move" in Rust: the compiler just infers the right thing to do. And of course since it's the language's d
by masklinn 10y ago
> The difference is that you don't have to write "std::move" in Rust: the compiler just infers the right thing to do.
And of course since it's the language's default you don't have to write a dozen lines of boilerplate either, this is the C++ code stripped of the interspersed text:
class MoveOnlyInt final {
private:
int i;
void release() { /* call to release function here */ }
public:
explicit MoveOnlyInt(int i) : i(i) {}
~MoveOnlyInt() { release(); }
MoveOnlyInt() = delete;
MoveOnlyInt(const MoveOnlyInt &) = delete;
MoveOnlyInt& operator=(const MoveOnlyInt &) = delete;
MoveOnlyInt(MoveOnlyInt &&other) { i = other.i; other.i = -1; }
MoveOnlyInt& operator=(MoveOnlyInt &&other) { release(); i = other.i; other.i = -1; return *this; }
operator int() const { return i; }
};
This seems like a fair Rust version, with as you noted the "move source" becoming inaccessible rather than just being in an invalid state:
struct MoveOnlyInt {
i: isize,
}
impl MoveOnlyInt {
fn new(i: isize) -> MoveOnlyInt { MoveOnlyInt { i: i } }
}
// Rust doesn't have an "operator int", this seems close enough
impl<'a> From<&'a MoveOnlyInt> for isize {
fn from(m: &'a MoveOnlyInt) -> isize { m.i }
}
- kibwen 10y agoThat's actually even way too much code for the Rust version. A wrapper type declaration is as simple as `struct MoveOnlyInt(i32);`, and construction is then just `let foo = MoveOnlyInt(42);`. (And of course, the wrapper type is only necessary because integers in Rust implement `Copy`, opting out of move semantics.)
- steveklabnik 10y ago(and "operator int" would be foo.0 in this case)
- mrout 10y agoIt's actually far too little code, as it leaves out all the code in the Rust compiler that implements this.
- heinrich5991 10y agoDon't use `isize`, `isize` is not equivalent to C's `int`, but `intptr_t`. Specific sizes would be best, but if you need to copy C's `int`, there's `libc::c_int`.