c++ - 从函数返回对局部变量的 const 引用

标签 c++ reference undefined const-reference

我有一些关于从函数返回对局部变量的引用的问题:

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
}

我的问题是 =>

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

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

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

最佳答案

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

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

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

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

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?

没有。下面是一个例子:

A const & newConstA3 = getA3 ();

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

关于c++ - 从函数返回对局部变量的 const 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1465851/

相关文章:

c++ - 只包含最后 n 个元素的 vector

c++ - OpenGL 游戏的主菜单

c# - 关于 C# 中对象引用类型转换的问题?

c# - 在 `ZipArchive` 命名空间中找不到 “System.IO.Compression”

C/C++ 错误 : Pointer variable undefined inside function

typescript - 从类型的属性中删除 null 或 undefined

c++ - 构造函数调用时的圆括号与大括号

c++ - 动态规划中这种初始化背后的直觉

c++ - 由引用 : what am I doing wrong? 引起的意外复制构造

jquery - jqgrid中的"Undefined"消息,"b.jgrid.formatter is undefined"