Live data from Hacker News

My favorite Rust function

blog.jabid.in

11–20 of 197 posts

Re: My favorite Rust function

#12

Earlier quoted context omitted.

The standard C++ way to free resources is the character '}'

Tell that to the enormous heap object you just forgot you made earlier.

It would work with an object held by unique_ptr though, exactly like this Rust example.

Re: My favorite Rust function

#13
post #9

Earlier quoted context omitted.

The standard C++ way to free resources is the character '}'

Rust has the exact same semantics there. Drop is useful when you need to explicitly notate that a value should end its life early.

void drop(unique_ptr&& x) {}

Would do the same in C++ for values held by unique_ptr: take ownership of the pointer and then free it.

Re: My favorite Rust function

#14
post #13
post #9

Earlier quoted context omitted.

Rust has the exact same semantics there. Drop is useful when you need to explicitly notate that a value should end its life early.

void drop(unique_ptr && x) {} Would do the same in C++ for values held by unique_ptr: take ownership of the pointer and then free it.

No, it would not free it. It takes a reference to the pointer and does nothing.

Re: My favorite Rust function

#16
I haven't used rust, so can you explain this to me:

If I do the rust equivalent of:

    def add1(x):
      return x + 1
    
    x = 1
    y = add1(x)
    z = add1(x)
then will x have been deallocated by the first call to add1 and will the second call to add1 fail?

[You can ignore the fact that I'm using numbers and substitute an object if that makes more sense in the context of allocating / deallocating memory in rust.]

Re: My favorite Rust function

#18
post #16

I haven't used rust, so can you explain this to me: If I do the rust equivalent of: def add1(x): return x + 1 x = 1 y = add1(x) z = add1(x) then will x have been deallocated by the first call to add1 and will the second call to add1 fail? [You can ignore the fact that I'm using numbers and substitute an object if that makes more sense in the context of allocating / deallocating memory in rust.]

It depends: if add1 borrows the value then this code is fine. If add1 takes ownership of the parameter then no, this will not work.
Post reply on HN