是否返回语句复制值 [英] Does return statement copy values

查看:15
本文介绍了是否返回语句复制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于范围问题,我对此感到疑惑.例如,考虑代码

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.

这篇关于是否返回语句复制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆