Re: Revistiing using return value as reference
On Dec 25, 3:00 pm, "Jim Langston" <tazmas...@rocketmail.com> wrote:
Foo& Bar( int Val )
{
return Foo( Val );
}
Will not work, can not convert Foo to Foo&
Should work, but not a very useful thing to do as local copy dies
immediately.
Foo Bar( int Val )
{
return Foo( Val );
}
int main()
{
Foo& Inst = Bar( 10 );
}
Does not work, same thing, can not convert Foo to Foo&.
Should also work. Something else is going on as that syntax is
compiling fine in my compiler.
Foo& Bar(int Val )
{
Foo Temp( Val );
return Foo( Val );
}
I think you meant to return Temp, no? That too should work, but as
with #1, isn't very useful.
int main()
{
Foo& Inst = Bar( 10 );
}
Does not work, checking the value of Val_ later shows garbage data
indicating the reference has become invalidated (as expected). Can anyone
remember the case where a temp value returned from a function can be used as
a reference and not invalidated immediately?
Here's some thoughts:
Foo g_foo;
class Y
{
protected:
Foo _x; // instance (or member) variable
static Foo _y; // class instance variable (i.e., a static)
public:
Foo& GetFoo();
Foo& GetFoo2();
};
Foo&
Y::GetFoo()
{
return _x;
}
Foo&
Y::GetFoo2()
{
static Foo localStaticFoo; // global to all instances of Y but only
accessible within GetFoo2.
return localStaticFoo;
}
int main()
{
Y y;
Foo& foo = y.GetFoo();
Foo& foo2 = y.GetFoo2();
Foo& foo3 = g_foo;
}
A reference has to 'point' to a preexisting instance of something
(i.e., must be initialized to something upon declaration-- note that
this also includes any references that you might have as class members
which must be initted in your constructors' init lists).
In your case where that instance was local, it satisfied your
compiler, but obviously didn't have any use as it was deleted
underneath you when the func exited. So, you have to couple that idea
with a longer living object (such as class member, static member, or
global).