Re: cast to non-const reference of a function's return object
From: tom_usenet (tom_usenet_at_hotmail.com)
Date: 06/02/04
- Next message: Herbert Straub: "Error, if compiled with -O3 (gettext)"
- Previous message: klaus triendl: "cast to non-const reference of a function's return object"
- In reply to: klaus triendl: "cast to non-const reference of a function's return object"
- Next in thread: klaus triendl: "Re: cast to non-const reference of a function's return object"
- Reply: klaus triendl: "Re: cast to non-const reference of a function's return object"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Wed, 02 Jun 2004 09:34:07 +0100
On Wed, 02 Jun 2004 08:09:01 GMT, "klaus triendl" <triendl.kj@mbox.at>
wrote:
>hi,
>
>recently i discovered a memory leak in our code;
I think you mean "use of a dangling reference" rather than "memory
leak".
after some investigation i
>could reduce it to the following problem:
>return objects of functions are handled as temporary objects, hence their
>dtor is called immediately and not at the end of the function. to be able to
>use return objects (to avoid copying) i often assign them to a const
>reference.
>now, casting a const return object from a function to a non-const reference
>to this return object calls immediately the dtor of the return object
>anyway, any further operation deals with a non-valid object then. if i do
>this in two steps - first holding a const reference to the return object and
>then const_casting it, everything works like i expected it.
>
>does anybody know whether the compiler behaves correctly?
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.
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.
Tom
-- C++ FAQ: http://www.parashift.com/c++-faq-lite/ C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
- Next message: Herbert Straub: "Error, if compiled with -O3 (gettext)"
- Previous message: klaus triendl: "cast to non-const reference of a function's return object"
- In reply to: klaus triendl: "cast to non-const reference of a function's return object"
- Next in thread: klaus triendl: "Re: cast to non-const reference of a function's return object"
- Reply: klaus triendl: "Re: cast to non-const reference of a function's return object"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|