Quantcast
Viewing latest article 1
Browse Latest Browse All 3

Answer by fred xia for Create owned value on demand

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.


Viewing latest article 1
Browse Latest Browse All 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>