Does return statement copy values(是否返回语句复制值)
问题描述
由于范围问题,我对此感到疑惑.例如,考虑代码
I am wondering about this because of scope issues. For example, consider the code
typedef struct {
int x1;/*top*/
int x2;/*bottom*/
int id;
} subline_t;
subline_t subline(int x1, int x2, int id) {
subline_t t = { x1, x2, id };
return t;
}
int main(){
subline_t line = subline(0,0,0); //is line garbage or isn't it? the reference
//to subline_t t goes out of scope, so the only way this wouldn't be garbage
//is if return copies
}
所以我的问题是,return 语句会一直复制吗?在这种情况下,它似乎有效,所以我被引导相信 return 确实复制了.如果它确实复制,它会在每种情况下都复制吗?
So my question is, will the return statement always copy? In this case it seems to work, so I am led to believe that return does copy. If it does copy, will it copy in every case?
推荐答案
是的,在这种情况下会有一个副本.如果您像这样更改函数声明:
Yes, in that case there will be a copy made. If you change the function declaration like this:
subline_t &subline(int x1, int x2, int id) {
那么不会复制.但是,在您的特定情况下,返回对堆栈上分配的对象的引用是无效的.问题是对象在调用者有机会使用它之前就被破坏并失效.
then no copy will be made. However, in your specific case it would not be valid to return a reference to an object allocated on the stack. The problem is that the object would be destructed and invalidated before the caller had a chance to use it.
这与 C++ 的常见 返回值优化 有关,可以避免进行实际复制在您描述的情况下进行操作.最终结果(或应该)与完成复制一样,但您应该注意优化.在某些情况下,这种优化的存在可以改变程序的可观察行为.
This is related to the common Return Value Optimization for C++ that can avoid doing an actual copy operation in the case you have described. The end result is (or should be) the same as if a copy were done, but you should be aware of the optimization. The presence of this optimization can, in some cases, change the observable behaviour of the program.
这篇关于是否返回语句复制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否返回语句复制值
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01