Member-only story
Rust vs C++: The 4-Line Bug That Explains Everything
Both languages are fast. The real difference is who has to prove your code is safe: you, or the compiler.
Four lines of C++. No warnings, no errors. It compiles, passes your tests, and ships. Then, weeks later, it crashes in production.
Here is the program:
#include <iostream>
#include <vector>int main() {
std::vector<int> v = {1, 2, 3};
int& first = v[0]; // a reference to the first element
v.push_back(4); // the vector may need to grow
std::cout << first << "\n"; // undefined behavior
}It looks harmless, but it isn’t. When a vector runs out of room, it allocates a bigger block of memory, copies the elements over, and frees the old block. Our reference first still points into the old block, so this is a use-after-free. C++ doesn't stop you. It just trusts you.
Now the same idea in Rust:
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
v.push(4);
println!("{}", first);
}This will not build. The compiler reports error E0502: you cannot borrow v as mutable because it is also borrowed as immutable. A bug that would have appeared in production at 3 a.m. becomes…








