Reference to temporary objects

Discussion in 'C++' started by Alexander Stippler, Mar 17, 2006.

  1. 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.
     
    Alexander Stippler, Mar 17, 2006
    #1
    1. Advertising

  2. Alexander Stippler

    Rolf Magnus Guest

    Alexander Stippler wrote:

    > 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();


    Right.

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


    Because C++ forbids binding non-const references to temporaries.

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


    Right.
     
    Rolf Magnus, Mar 17, 2006
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Andy Buckley
    Replies:
    5
    Views:
    343
    Victor Bazarov
    Aug 26, 2004
  2. Ariel
    Replies:
    2
    Views:
    416
    Ariel
    Nov 3, 2004
  3. Replies:
    5
    Views:
    359
    Victor Bazarov
    Jun 24, 2005
  4. 7stud
    Replies:
    11
    Views:
    711
    Dennis Lee Bieber
    Mar 20, 2007
  5. Replies:
    7
    Views:
    3,261
    James Kanze
    Feb 12, 2008
Loading...

Share This Page