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
}
我的问题是 =>
getA1()
的实现是否正确?我觉得这是不正确的,因为它返回的是局部变量或临时变量的地址.
Is the implementation of
getA1()
correct? I feel it is incorrect as it is returning the address of a local variable or temporary.
main
(1,2,3) 中的哪些语句会导致未定义的行为?
Which of the statements in main
(1,2,3) will lead to undefined behavior?
在const A&newA1 = getA1();
标准是否保证在引用超出范围之前不会破坏由 const 引用的临时绑定?
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()
实现是否正确?我觉得这是不正确的,因为它返回的是局部变量或临时变量的地址.
1. Is
getA1()
implementation correct ? I feel it is incorrect as it is returning address of local variable or temporary.
在您的程序中唯一正确的 getAx()
版本是 getA3()
.无论您以后如何使用它们,其他两个都有未定义的行为.
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.main (1,2,3) 中的哪个语句会导致未定义行为?
2. Which of the statements in main ( 1,2,3) will lead to undefined behavior ?
从某种意义上说,他们都没有.对于 1 和 2,未定义的行为是函数体的结果.对于最后一行,newA3
应该是一个编译错误,因为您不能将临时引用绑定到非 const 引用.
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.在 const A&newA1 = getA1();
做标准保证由 const
临时绑定除非引用超出范围,否则引用不会被销毁?
3. In
const A& newA1 = getA1();
does standard guarantees that temporary bound by aconst
reference will not be destroyed until the reference goes out of scope?
没有.下面是一个例子:
No. The following is an example of that:
A const & newConstA3 = getA3 ();
这里,getA3()
返回一个临时对象,该临时对象的生命周期现在绑定到对象 newConstA3
.换句话说,临时文件将一直存在,直到 newConstA3
超出范围.
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.
这篇关于从函数返回对局部变量的常量引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从函数返回对局部变量的常量引用


基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01