Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

c++ - Returning const reference to local variable from a function

I have some questions on returning a reference to a local variable from a function:

class A {
public:
    A(int xx)
    : x(xx)
    {
        printf("A::A()
");
    }
};

const A& getA1()
{
    A a(5);
    return a;
}

A& getA2()
{
    A a(5);
    return a;
}

A getA3()
{
    A a(5);
    return a;
}

int main()
{
    const A& newA1 = getA1(); //1
    A& newA2 = getA2(); //2
    A& newA3 = getA3(); //3
}

My questions are =>

  1. Is the implementation of getA1() correct? I feel it is incorrect as it is returning the address of a local variable or temporary.

  2. Which of the statements in main (1,2,3) will lead to undefined behavior?

  3. In const A& newA1 = getA1(); does the standard guarantee that a temporary bound by a const reference will not be destroyed until the reference goes out of scope?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

1. Is getA1() implementation correct ? I feel it is incorrect as it is returning address of local variable or temporary.

The only version of getAx() that is correct in your program is getA3(). Both of the others have undefined behaviour no matter how you use them later.

2. Which of the statements in main ( 1,2,3) will lead to undefined behavior ?

In one sense none of them. For 1 and 2 the undefined behaviour is as a result of the bodies of the functions. For the last line, newA3 should be a compile error as you cannot bind a temporary to a non const reference.

3. In const A& newA1 = getA1(); does standard guarantees that temporary bound by a const reference will not be destroyed until the reference goes out of scope?

No. The following is an example of that:

A const & newConstA3 = getA3 ();

Here, getA3() returns a temporary and the lifetime of that temporary is now bound to the object newConstA3. In other words the temporary will exist until newConstA3 goes out of scope.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...