when I call:std::cout << a->get_val() << std::endl; the local variable temp still exist. what they teached me that in c++ the local variable will be deleted after exiting from Func. any explanation guys?
thanks
This function returns an integer. Now, when it returns, the return value is copied so the value received by the caller is not the same variable, but a copy thereof. Hence, although any local variables in the called function are no longer alive, the return value will have been copied out successfully.
I'm not sure what you mean by this:
the local variable temp still exist
The variable temp is never attempted to be accessed outside the function Counter::operator++().
You are returning a reference to a temporary object, so - for the very reason you have posted - the return value is useless. Instead return by value (i.e. change Counter& to Counter. Note also that instead of needlessly creating an additional copy, you can just do this:
1 2 3 4 5
Counter operator++()
{
++val;
return *this; // deference the pointer to the current class and return that value
}
"
I RETURN REFERENCE FOR LOCAL VARIABLE WHICH IS "temp".
When I call from main (little changes in it)"
1 2 3 4 5 6 7 8 9 10 11 12
int main(){
Counter i;
i.Increment(); // 1
++i;
std::cout << i.get_val() << std::endl; // 2
Counter* a = &( ++i );// I get pointer to the returned reference of local variable temp
std::cout<<std::endl<<a<<std::endl;
std::cout << a->get_val() << std::endl; // // well it print '3'. temp still exist isn't it?
return 0;
}
"
and my output:
1 2 3 4 5 6 7 8 9
./byval
0xbfc0462c
2
0xbfc0462c
0xbfc0462c
3
local variable still exist after I finish the function. !!!
No, the local variable no longer exists. You are not reading data from temp because temp isnt' there anymore. What you're reading is garbage/leftover RAM. This is very unsafe to do.
EDIT:
I removed my example because whether or not is exposes the problem depends entirely on the compiler's optimization settings.
Just trust us, 'temp' no longer exists. By returning a reference like that, you are doing "very bad things". 'a' is a bad pointer.