Returning a reference to a temporary

M

marco_segurini

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.
 
D

Dietmar Kuehl

marco_segurini said:
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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,054
Latest member
LucyCarper

Latest Threads

Top