2 ms·
This has surprised me on occasion. Shouldn't the compiler be smart enough to figure out how long to keep it around for, instead of failing to compile?
by iknowstuff 7y ago
This has surprised me on occasion. Shouldn't the compiler be smart enough to figure out how long to keep it around for, instead of failing to compile?
- steveklabnik 7y agoOne could argue that the compiler could transform this for you. But systems languages are also about control. For someone versed in the way things are supposed to work, an owned value living longer than it should is surprising. Tradeoffs, tradeoffs.
- tylerhou 7y agoThe compiler is smart enough to deduce lifetimes — that’s why it can throw a compile error — but fixing them (auto-keeping temporaries) might introduce extra memory consumption/leaks that the programmer did not intend. Requiring the programmer to explicitly assign a temporary to a variable makes the programmer’s intent more clear. A comparison: in C++, the behavior of auto-extending the lifetime of const references to temporaries (but not non-const references) is considered a wart in the language design. (Really, you should just assign a temporary to a value because the compiler can elide the copy. : https://abseil.io/tips/101 https://abseil.io/tips/101 .)