References again

From: JKop (NULL_at_NULL.NULL)
Date: 06/18/04


Date: Fri, 18 Jun 2004 16:17:57 GMT

Take the following:

int GiveMeInt(void)
{
        return 734;
}

int main(void)
{
        const int& plain = GiveMeInt();
        
        //Time goes by

            TakeConstIntPointer(&plain);
}

I know that there's nothing wrong with the above because the reference has
extended the life of the variable.

But take the following:

int& GiveMeIntRef(void)
{
        int cow = 343;
        
        return cow;
}

int main(void)
{
        const int& ref = GiveMeIntRef();

            //Time goes by

            TakeConstIntPointer(&ref);
}

Has the lifetime been extended in the above?? Or am I accessing a variable
that no longer exists? If so, should I take the following as a general
guidline: Only return a reference from a function if it was declared via
new. ?

-JKop



Relevant Pages