I was watching this video (timestamp), and this code exhibits undefined behavior.
struct S {
std::vector<int> data{1, 2, 3, 4, 5};
const auto& get_data() const { return data; }
};
S get_s() { return S{}; }
int main() {
for (const auto &v : get_s().get_data()) {
std::cout << v;
}
}
He says that the expanded version of the for
is exactly this, which I understand.
auto && __range = get_s().get_data(); // This line
auto __begin = begin(__range);
auto __end = end(__range);
for (; __begin != __end; ++__begin()) {
std::cout << v;
}
Auto ref-ref would extend the lifetime of the thing returned by
get_s
, not the thing returned byget_data
.
I don't think he misspoke either, as he goes on to say
[...] dangling reference to the object of type S
Why is that so? Shouldn't the RHS be completely evaluated before assignment to the LHS?
Also, not sure how to title this question, or what to exactly search for, please let me know so that I can better search for resources next time. Thanks.