On Wed, 02 Jun 2004 14:07:20 GMT, "klaus triendl" <triendl.kj@mbox.at>
wrote:
[color=blue][color=green]
>> Yes, binding a temporary directly to a const reference extends the
>> lifetime of the temporary to match that of the reference. You can't
>> bind a temporary to a non-const reference, so there's no way of doing
>> the lifetime extension using a non-const ref.[/color]
>if the temporary is non-const i can bind it to a non-const reference. at
>least with vc++7 it is possible.[/color]
This is a non-conforming compiler extension. On VC7.1 I get a warning,
and compiling with /Za (ISO mode) I get an error.
[color=blue]
>[color=green]
>> Note, since you return a const string, using the returned string as a
>> non-const string results in undefined behaviour. You can only safely
>> use an object that has had const cast away as a non-const object if it
>> wasn't originally declared const.[/color]
>well, that's an argument; and i can easily solve that problem.[/color]
Indeed, that paragraph was just an aside.
[color=blue]
>but my question still remains whether the const_cast in the function
>"funcWmemleak" is a good reason that the non-const reference is a non-valid
>object after the assignment or not.[/color]
If you perform the const_cast, then you are not directly binding the
reference to the temporary, and the lifetime will not be extended,
hence you have a "dangling reference" that you can't use. It is
synonymous to this conforming code that exhibits the same problem, and
doesn't use any Microsoft extensions:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string const& s = static_cast<string const&>(string("foo"));
cout << s << '\n';
}
Because s isn't bound directly to the temporary (it is bound to the
result of the static cast), it doesn't extend the temporary's lifetime
and the cout call has undefined behaviour since the temporary has
already been destroyed. Remove the static_cast and it's fine. See
12.2/5 in the C++ standard.
Clear?
Tom
--
C++ FAQ:
http://www.parashift.com/c++-faq-lite/
C FAQ:
http://www.eskimo.com/~scs/C-faq/top.html