Use a non-refence variable to receive a refernce-type returning value

I have a function as below:
template<class T>
T& Front()
{
T a = 100;
return a;
}

In the main function, I have:

T b = Front();

In the Visual C++ 2008 compiler, there is a warning:
warning C4172: returning address of local variable or temporary.

I know a is a local variable in Front() and will be released after Front() ends. However, "T b = Front()" always has the correct value for b. I have shown the address of a, the variable in Front(), and b, and found that their addresses are actually different, which means this is in fact a "hard copy", rather than a "soft copy". I guess although the compiler gives such a warning, it automatically turn into a hard copy because it sees that b is a actually a non-reference type.

However, I don't like to see the warnings when I compile my program. Is there a way to better program it so that the same functionality is realized without warning of risks? Yes, it could be changing the returning type T& to T, since the system actually does that when it meets b, but what I really want to know is: In STL, a lot of data structure, such as queue, have a front(), which always return a reference-type value of its first element. If you use T b = myqueue.front() to get the first element, there is no warning during compilation. I want to know why they have no such a problem.

Thanks for comments and answering my questions!
T b = Front(); calls the copy constructor so it is a "hard copy"

Is there a way to better program it so that the same functionality is realized without warning of risks?
Never return references to function-local variables

In STL, a lot of data structure, such as queue, have a front(), which always return a reference-type value of its first element.
The first element of the data structure doesn't get out of scope when the function returns
a in Front() goes out of scope before b is assigned to the value pointed to by the reference returned by Front() (boy, that was a long phrase). If T happened to be a type with non-trivial constructors and destructor, or if something wrote to where a used to be (although that's somewhat unlikely, I think), you'd be fucked.

Returning a reference to a local object has undefined behavior. Don't do it.
Topic archived. No new replies allowed.