C++ 从函数返回对局部变量的常量引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1465851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:05:17  来源:igfitidea点击:

Returning const reference to local variable from a function

c++referenceundefinedconst-reference

提问by aJ.

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()\n");
    }
};

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?

  1. 执行getA1()是否正确?我觉得这是不正确的,因为它返回的是局部变量或临时变量的地址。

  2. main(1,2,3) 中的哪个语句会导致未定义的行为?

  3. const A& newA1 = getA1();做标准的保证,暂时由const引用约束不会被破坏,直到那张参考范围呢?

采纳答案by Richard Corden

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

1.getA1()实施是否正确?我觉得这是不正确的,因为它返回的是局部变量或临时变量的地址。

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.

getAx()在您的程序中唯一正确的版本是getA3(). 无论您以后如何使用它们,其他两个都有未定义的行为。

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

2. main (1,2,3) 中的哪个语句会导致未定义的行为?

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, newA3should be a compile error as you cannot bind a temporary to a non const reference.

从某种意义上说,他们都没有。对于 1 和 2,未定义的行为是函数体的结果。对于最后一行,newA3应该是编译错误,因为您不能将临时引用绑定到非 const 引用。

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

3.const A& newA1 = getA1();标准是否保证const在引用超出范围之前不会破坏引用的临时绑定?

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 newConstA3goes out of scope.

在这里,getA3()返回一个临时对象,并且该临时对象的生命周期现在绑定到 object newConstA3。换句话说,临时文件将一直存在,直到newConstA3超出范围。

回答by dharga

Q1: Yes, this is a problem, see answer to Q2.

Q1:是的,这是一个问题,请参阅 Q2 的答案。

Q2: 1 and 2 are undefined as they refer to local variables on the stack of getA1 and getA2. Those variables go out of scope and are no longer available and worse can be overwritten as the stack is constantly changing. getA3 works since a copy of the return value is created and returned to the caller.

Q2:1 和 2 未定义,因为它们引用了 getA1 和 getA2 堆栈上的局部变量。这些变量超出范围,不再可用,更糟糕的是,随着堆栈不断变化,可能会被覆盖。getA3 起作用,因为创建了返回值的副本并将其返回给调用者。

Q3: No such guarantee exists to see answer to Q2.

Q3:不存在这样的保证来查看 Q2 的答案。

回答by Arkaitz Jimenez

I think the main problem is that you are not returning temporaries at all, you should

我认为主要的问题是你根本没有返回临时工,你应该

return A(5);

rather than

而不是

A a(5);
return a;

Otherwise you are returning local variable address, not temporary. And the temporary to const reference only works for temporaries.

否则,您将返回局部变量地址,而不是临时地址。而临时到 const 引用仅适用于临时对象。

I think its explained here: temporary to const reference

我认为它在这里解释: 临时到常量引用

回答by Satbir

If you will compile this on VC6 you will get this warning

如果您将在 VC6 上编译它,您将收到此警告

******Compiler Warning (level 1) C4172 returning address of local variable or temporary A function returns the address of a local variable or temporary object. Local variables and temporary objects are destroyed when a function returns, so the address returned is not valid.******

******编译器警告(级别 1) C4172 返回局部变量或临时对象的地址 函数返回局部变量或临时对象的地址。函数返回时会销毁局部变量和临时对象,因此返回的地址无效。******

While testing for this problem i found interesting thing (given code is working in VC6):

在测试这个问题时,我发现了有趣的事情(给定的代码在 VC6 中工作):

 class MyClass
{
 public:
 MyClass()
 {
  objID=++cntr;
 }
MyClass& myFunc()
{
    MyClass obj;
    return obj;
}
 int objID;
 static int cntr;
};

int MyClass::cntr;

main()
{
 MyClass tseadf;
 cout<<(tseadf.myFunc()).objID<<endl;

}