A Question On Reference Type

This is a discussion on A Question On Reference Type within the C++ Programming forums, part of the General Programming Boards category; No. The former declares a function named t that takes no arguments and returns a Test. The latter is not ...

Visual C++ is a known compiler to allow this extension. If you go to warnings level 4, you should also receive a warning saying non-standard extension used.
The extension allows you to bind a non-const reference to a temporary, which is disallowed by the standard (only const references can bind to temporaries, which has been pointed out earlier).

Unless you use new, it's on the stack. Always the stack, unless it's new.
I believe it's because you shouldn't be able to modify a temporary because it's just that - a temporary. Its lifetime is less than that of the variable it's bound to. Bad things would happen if you try to modify it after its lifetime has expired (while the lifetime of the variable holding the reference is still alive).

That's one thing that has burned me a number of times... What exactly is the lifetime of a temporary object? It's obviously less than a regular variable which ends when it gets to its closing brace.
I think this is one of the cases where I've gotten burned:

>> When I disabled extension it generates error for my type cast. So how should I cast that?
Why do you need a cast there? Just output this (or cast to void*).

Temporaries passed to a function live until the function ends, but in cpjust's example the result of Func() isn't passed to a function, a pointer is. So the result of Func() lives until c_str() is called and it's value is sent to the function. Then it can be destroyed.

A temporary lives until the end of the "full-expression", i.e. the next semicolon. Unless, that is, it is bound to a reference, in which case its lifetime is extended to that of the reference.

In particular, a temporary appearing with function parameters lives until the full expression containing the function call finishes. However, if the function keeps a reference to the object in question, this reference will soon be invalid.