Returning a reference to a temporary

Discussion in 'C++' started by marco_segurini, Jan 10, 2005.

  1. Hi,
    I like to know if the statement at line 15 is correct or not.

    #include <vector>

    class Descriptor
    {
    private:
    enum { TYPE_0, TYPE_MAX };
    Descriptor & Init0()
    {
    return *this;
    }
    public:
    static void Init(std::vector<Descriptor> & vDescr)
    {
    vDescr.reserve(TYPE_MAX);
    vDescr.push_back(Descriptor().Init0()); // line 15
    }
    };

    TIA.
    Marco.
    marco_segurini, Jan 10, 2005
    #1
    1. Advertising

  2. marco_segurini wrote:
    > Descriptor & Init0()
    > {
    > return *this;
    > }
    > public:
    > static void Init(std::vector<Descriptor> & vDescr)
    > {
    > vDescr.reserve(TYPE_MAX);
    > vDescr.push_back(Descriptor().Init0()); // line 15
    > }


    This is OK since temporary live until the end of the full
    expression. However, you can actually 'push_back()' the
    temporary directly without a call ot 'Init0()' as the
    generated copy constructor takes a 'const&' parameter anyway.
    --
    <mailto:> <http://www.dietmar-kuehl.de/>
    <http://www.contendix.com> - Software Development & Consulting
    Dietmar Kuehl, Jan 10, 2005
    #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. Alexander Stippler
    Replies:
    2
    Views:
    624
    Alexander Stippler
    Jul 4, 2003
  2. qazmlp
    Replies:
    3
    Views:
    386
    Claudio Puviani
    Mar 7, 2004
  3. Replies:
    7
    Views:
    3,204
    James Kanze
    Feb 12, 2008
  4. AdlerSam
    Replies:
    10
    Views:
    2,964
    James Kanze
    Feb 22, 2011
  5. JustMe
    Replies:
    1
    Views:
    170
    Tassilo v. Parseval
    Aug 29, 2003
Loading...

Share This Page