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?