0

I have following code which I run with g++ on my mac and visual studio on windows:

#include <iostream>

using namespace std;

const string& foo() {
   string a = "hello";
   return a;
}

int main() {
   string s = foo();
   cout << s << endl;
   return 0;
}

This code should fail runtime:

From Marc Gregori's "Professional c++", page 278:

"WARNING: From function or method, never return a reference to a variable that is locally scoped to that function or method, such as an automatically allocated variable on the stack will be destroyed when the function ends."

It throws exception in Visual c++, but why it works with g++ (pple LLVM version 8.0.0 (clang-800.0.42.1))?

(It shows warning, but still, works and outputs "hello" string").

Is g++ "smarter" and returns copy value of local object if it sees such code?

Teimuraz
  • 8,795
  • 5
  • 35
  • 62
  • 1
    Because UB is UB. – Jarod42 May 12 '17 at 16:38
  • 1
    No, g++ is not smarter. It just fails in a way that looks like it's working (for now). – melpomene May 12 '17 at 16:43
  • What do you mean by "it works with g++"? It does the thing you least expect it to do. In what sense would you describe that as working? – David Schwartz May 12 '17 at 16:43
  • @DavidSchwartz, it outputs "hello". Or do you mean this is not guaranteed behavior? – Teimuraz May 12 '17 at 16:49
  • 1
    @moreo Did you expect it to output "hello"? If so, why? If not, then why would you describe outputting "hello" as working? – David Schwartz May 12 '17 at 17:03
  • Not guaranteed. This is you getting unlucky. The C++ Standard defines what the program does when the rules are followed, but generally doesn't specify any handling if the rules are broken. The memory has been freed, but maybe the memory manager will let the program keep it so it doesn't have to allocate it again later. Maybe it's sitting on a stack and hasn't been overwritten yet. Whole lot of maybes, and trying to define the outcome of all of them is an insane task. – user4581301 May 12 '17 at 17:13

0 Answers0