返回语句的副本值 [英] Does return statement copy values

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

问题描述

我想知道这是因为范围问题。例如,考虑代码

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
}

所以我的问题是,返回语句总是复制吗?在这种情况下它似乎工作,所以我导致相信返回复制。如果它复制,它会在每种情况下复制吗?

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.

这与常见的还原值优化,可以避免在您描述的情况下进行实际的复制操作。最终结果是(或应该)与复制完成相同,但您应该知道优化。在某些情况下,这种优化的存在可以改变程序的可观察行为。

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天全站免登陆