The code is somewhat equivalent to the C++ code below:
#include <string>int main(){ auto condition = false; std::string a("a"); const std::string* ptr; if (condition) { ptr = &a; } else { std::string b("b"); ptr = &b; }}
If you are familiar with C++ you will see that ptr
has the address of b
, which is freed after code execution exits else {...}
block. So ptr
is pointing to an invalid memory address.
C++ compiler won't complain. This code will pass the C++ compiler. However code like this will have runtime problems. It's a good thing that Rust compiler catches such error at compile time, and force you to make sure that the lifetime of a copy of b
is stored in r
.