Recently, I was reading C++ Primer, and it said:
When a function completes, its storage is freed. After a function terminates, references to local objects refer to memory that is no longer valid
So, I type the following code in my Visual Studio 2019:
int& returnRef()
{
int n = 2;
return n;
}
int main()
{
int ref = returnRef();
cout << ref;
}
I thought it should be a case error, but it didn't and printed the correct value on command. I was confused. Is there an explanation for this?
I am new to C++.
Edit:
Thanks guys/gals. It looks like this problem is about the compiler. I got it.
BTW, I posted another question about enabling compiler warnings in vs2019: How can I enable compiler warnings in Visual Studio 2019?