3 ms·
Problem is, you call pop on empty vector in C++, you get nasal demons. Not a case in Rust. I'm not a C++ expert but here is my understanding. Vector is essenti
by Ygg2 3y ago
Problem is, you call pop on empty vector in C++, you get nasal demons. Not a case in Rust.
I'm not a C++ expert but here is my understanding. Vector is essentially a tuple of (dynamic_array_address: ptr, size: size_t, capacity: size_t). To pop a value from vector you just decrements size. So what happens when you have empty vec? Your size is 0, and you're substracing 1, which causes undefined behavior.
Correct way is to check BEFORE you pop_back().
In Rust, any number of invocation of pop() will not result in undefined behavior. You can ignore the value, or you can check it, but it doesn't expose you to UB just for slightly misusing a vector.
- FpUser 3y ago>"Correct way is to check BEFORE you pop_back()" Absolutely and this is exactly what I do. I always check the containers before removing elements. >"In Rust, any number of invocation of pop() will not result in undefined behavior. You can ignore the value, or you can check it, but it doesn't expose you to UB just for slightly misusing a vector." I do not understand "slightly misusing" part. I assume in Rust it would bomb if pop() returns "none" and you try for example add said "none" to some number.
- aldonius 3y agoVec<T>::pop() and similar methods return an Option<T>, so it's a compile-time type error to just add a number to it directly.
- Ygg2 3y ago> I assume in Rust it would bomb if pop() That's the thing. It wouldn't. Worse you can do is make whole program panic, with well defined stack trace and message. It will never return non-sense and pretend all is ok.