Connecting Tech Pros Worldwide Forums | Help | Site Map

Returning a reference to a temporary

marco_segurini
Guest
 
Posts: n/a
#1: Jul 23 '05
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.

Dietmar Kuehl
Guest
 
Posts: n/a
#2: Jul 23 '05

re: Returning a reference to a temporary


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

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:dietmar_kuehl@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.contendix.com> - Software Development & Consulting

Closed Thread