Hacker News new | ask | show | jobs
by needlesslygrim 881 days ago
You're mostly correct, it is moved into the function (pass by value), and then, at the end of the function's scope, the destructor is called automatically (as the compiler inserts a call to `drop()` at the end of the function) which de-allocates the vec, causing the reference obtained in `main()` become a dangling pointer.
1 comments

Thank you!
An alternative, more correct but less interesting, explanation: you really need to look at the disassembly (with your specific build of the Rust compiler with the same flags) to see what's really happening. This is why UB (undefined behavior) is dangerous.

For example, the compiler could decide that the entire allocation is unnecessary and elide it, if it's known that the Vec is very small. The compiler could also decide to pass it by ref. Remember that the compiler merely has to preserve your intent, beyond that it is allowed to do whatever it pleases.

https://rust.godbolt.org/