Reference to temporary objects

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

    #1

    Reference to temporary objects

    Here my code snippet:

    //----------------------

    struct Thing
    {
    };

    template <typename T>
    struct Wrap
    {
    operator T &()
    {
    return t;
    } }

    T t;
    };

    Wrap<Thing>
    func()
    {
    return Wrap<Thing>();
    }

    //------------------------

    And here my question:

    // 1) Ok, lifetime of returned temporary is bound to "a"
    const Wrap<Thing> &a = func();

    // 2) Not allowed, why?
    Wrap<Thing> &a = func();

    // 3) Not ok. "a" references an object that gets destroyed
    Thing &a = func()

    Here my questions:

    why is 2) not allowed?

    regarding 3):
    I was reading 12.2 in the standard:
    "The second context is when a reference is bound to a temporary. The
    temporary to which the reference is bound or the temporary that is the
    complete object to a subobject of which the temporary is bound persists
    for the lifetime of the reference except as specified below".

    Well I couldn't see that the "things below" match.
  • Rolf Magnus

    #2
    Re: Reference to temporary objects

    Alexander Stippler wrote:
    [color=blue]
    > Here my code snippet:
    >
    > //----------------------
    >
    > struct Thing
    > {
    > };
    >
    > template <typename T>
    > struct Wrap
    > {
    > operator T &()
    > {
    > return t;
    > } }
    >
    > T t;
    > };
    >
    > Wrap<Thing>
    > func()
    > {
    > return Wrap<Thing>();
    > }
    >
    > //------------------------
    >
    > And here my question:
    >
    > // 1) Ok, lifetime of returned temporary is bound to "a"
    > const Wrap<Thing> &a = func();[/color]

    Right.
    [color=blue]
    > // 2) Not allowed, why?
    > Wrap<Thing> &a = func();[/color]

    Because C++ forbids binding non-const references to temporaries.
    [color=blue]
    > // 3) Not ok. "a" references an object that gets destroyed
    > Thing &a = func()[/color]

    Right.

    Comment

    Working...