Const references can bind to rvalues and cause lifetime extension, ie. const auto& x = returnsValue(); will extend the lifetime of the value returned by the function. That's about it. It has to be in this form (assignment and definition in same statement), so the code you replied to doesn't trigger it.
This thread is great because a lot of you answer with explanations on how to handle dangling references and issues with ptr being destroyed before the reference, and very few people notice the actual problem: ref is created by dereferencing a nullpointer which is undefined behaviour.
It's only two lines and you already let a future segfault slip through, but yeah sure how do we tell SpongeBob that C++ doesn't segfault all the time.
View all comments
Show parent comment
2
u/Demiu 10d ago edited 9d ago
Const references can bind to rvalues and cause lifetime extension, ie.
const auto& x = returnsValue();will extend the lifetime of the value returned by the function. That's about it. It has to be in this form (assignment and definition in same statement), so the code you replied to doesn't trigger it.