Hacker News new | ask | show | jobs
by GlitchMr 2087 days ago
Rust doesn't prevent memory leaks.

However, it may help in this specific case.

In your example you are iterating over `m_requests_to_process`. As you are using `auto` instead of `auto &` it automatically clones the elements of a vector. In Rust, it's not possible to clone an element by accident. Objects are moved by default (think `std::move`) and if you want to clone instead you need explicitly use `.clone()`.

If `do_stuff` function takes ownership of a request (as in, if it takes `Request` parameter and not `&mut Request` parameter) than the problem will be pointed by Rust, and so the compiler wouldn't allow you write code like this forcing programmer to write code that removes elements from the list to take ownership of them. For example:

    for req in mem::take(&mut self.requests_to_process) {
        do_stuff(req);
    }
`mem::take` (https://doc.rust-lang.org/std/mem/fn.take.html) replaces an object behind a mutable reference with a default value for a given type (empty vector in case of vectors) and gives you an ownership over vector.
2 comments

You don't even need `std::mem::take`, you can just `drain` the `Vec`. This also allows the allocation to be reused, unlike your `mem::take` which ends up dropping the allocation.

`Vec::drain`: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.dra...

imagine that my struct request looks like

   struct request { 
     int id;
     double parameter_value;
   };
surely moving does not gain anything - the original vector object still keeps the memory allocated, right ? sure, if you have complex requests with substrings, etc, but in that case I'd have `const auto&`-ed :)

(from my experience going full-throttle on movability when C++11 came out, I'd say that this was a mistake overall, much better to keep things as const& most of the time if you can. I've not yet reached a state where I consider the need for ownership transfer a code smell... but not very far :-))

With the implementation your parent posted, the entire vector would be replaced with a fresh one. So the original vector would be deallocated entirely.

You could also do something with the drain method (which they posted originally and changed to the current implementation, not 100% sure why) and that would keep the memory around, yes, but then you'd be with only the high water mark of the number of requests, because it would be re-used.