0
const int& foo() {
  return 42;
}

int main() {
  foo();
}

Does this code have UB? Or I need to access the reference to trigger it?

cppbest
  • 59
  • 8
  • 1
    You cannot return a literal. Instead, a temporary local is created (for the reference), and that local is returned, which is UB. (BTW, your compiler should complain about this as a straight-up error anyway.) – Dúthomhas Dec 21 '22 at 05:35
  • 4
    Returning a reference to a local variable isn't UB, dereferencing it is (and 42 will be a stack variable). And why would you even care? It is obviously in a dangerous area, and not needed so just stay away from it. (Sometimes I have a hard time understanding peoples obsession with UB, 9 out of 10 it are programming errors, using C++ out of spec) – Pepijn Kramer Dec 21 '22 at 05:36
  • 1
    Not sure what part of the standard we could quote. Returning a reference to temporary is not UB until you deference it, so there's nothing to quote other than the general "dereferencing dangling references is UB". – HolyBlackCat Dec 21 '22 at 05:39
  • @PepijnKramer well, yes, but I want to know the correct answer for educational reasons (that's why it's a [tag:language-lawyer] question, which means I want a standardese answer) – cppbest Dec 21 '22 at 05:40
  • 5
    @HolyBlackCat is right though. We can't prove a negative. I mean, we can cite the section that says "it's invalid to dereference a pointer to freed memory", but I'm guessing you're already intimately aware of that section of the standard. There's no sentence that's going to say "temporary references can be returned but not dereferenced" because it's just never come up. There's no rule against returning a reference, and there's no rule against holding a reference to freed memory, provided you do nothing with it. The standard doesn't write out all of the things that are *not* rules. – Silvio Mayolo Dec 21 '22 at 05:42
  • I understand, but there is as Silvio said no "rules" for when the compiler should fail (if at all). For me the wording is clear too. Don't return references (or pointers) to local variables because you will use C++ out of spec. About the "lawyer" stuff, I still kind of find it funny since the standard isn't some watertight legal document. I mean it really tries to do a good job but there are holes (and interpretation differences). So it is good we have 3 compilers to find those holes :) – Pepijn Kramer Dec 21 '22 at 06:46
  • @cppbest - *"I want to know the correct answer for educational reasons"*. I get the feeling that you might be wasting your effort. I have used C++ for over 30 years, and this use case has never come up. Perhaps you should *first* find a good way to use a feature, and *then* figure out how it works. You know that the language standard is over 2000 pages, right? And nobody, not even Bjarne, knows **all** of it. – BoP Dec 21 '22 at 08:48

0 Answers0