Temporaries bind to const reference

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • kaede

    Temporaries bind to const reference

    Hi all,

    I would like to know if the following code is valid and not
    ill-formed.

    Data getData()
    {
    return Data(1, 2, 3);
    }

    void processData(con st Data& data)
    {
    // ... work with data ...
    }


    // ... in some code somewhere ...
    processData( getData() );

    Will this const reference initialized with getData() [temporaries]
    make that temporary value live for the lifetime of the reference
    itself?

    Thanks,
    Kaede
  • Kevin Goodsell

    #2
    Re: Temporaries bind to const reference

    kaede wrote:
    [color=blue]
    > Hi all,
    >
    > I would like to know if the following code is valid and not
    > ill-formed.
    >
    > Data getData()
    > {
    > return Data(1, 2, 3);
    > }
    >
    > void processData(con st Data& data)
    > {
    > // ... work with data ...
    > }
    >
    >
    > // ... in some code somewhere ...
    > processData( getData() );[/color]

    The code is valid (as far as I can tell - it's incomplete, after all).
    [color=blue]
    >
    > Will this const reference initialized with getData() [temporaries]
    > make that temporary value live for the lifetime of the reference
    > itself?[/color]

    I don't think that's precisely correct. Temporaries (usually) live until
    the end of the full expression in which they are created. There are
    exceptions to this, but I don't believe they apply here. In this case,
    the full expression ends *after* the call to processData() returns,
    therefore it has nothing to do with references - that temporary would
    live until the function completed whether you used a reference or not.

    -Kevin
    --
    My email address is valid, but changes periodically.
    To contact me please use the address from a recent posting.

    Comment

    Working...