简体   繁体   English

Operator =:返回参考值与值

[英]Operator=: return reference vs. value

I was going through this and am a bit confused. 我正在经历这个并且有点困惑。 Suppose that I declare a class as: 假设我将类声明为:

class cls
{
public:
    int x;
    cls(int _x):x(_x){}
    cls& operator=(cls& ob)
    {
        x = ob.x;
        return *this;
    }
};

And then create 2 objects and perform copy operation and then print the addresses of both the variables before and after the assignment operator is overloaded as: 然后创建2个对象并执行复制操作,然后在赋值运算符重载之前和之后打印两个变量的地址:

cls o1 = 7;
cls o2 = cls(8);
cout<<&o1<<endl;    //0330F880
cout<<&o2<<endl;    //0330F874
o1 = o2;
cout<<&o1<<endl;    //0330F880
cout<<&o2<<endl;    //0330F874

Both the address group is same; 地址组都是一样的; this is understood as the assignment operator returns by reference. 这被理解为赋值运算符通过引用返回。

But I notice that the same address group values are returned if I define my assignment operator to return by value. 但是我注意到,如果我将赋值运算符定义为按值返回,则会返回相同的地址组值。

In the link referred above, It is answered that a copy of the object will be returned if returned by value. 在上面提到的链接中,如果按值返回,则会回答该对象的副本。 Then why is it returning the same address values. 那为什么它返回相同的地址值。 Shouldn't they be different. 他们不应该是不同的。 Please help clear my concepts. 请帮助清除我的概念。

The return value is only relevant if you do something with it. 返回值仅在您使用它时才有意义。 For example: 例如:

(o1 = o2).do_something();

Or equivalently: 或等效地:

(o1.operator=(o2)).do_something();

The do_something() method will run on the object returned - in your case the original instance of o1 since it was returning a reference. do_something()方法将在返回的对象上运行 - 在您的情况下是o1的原始实例,因为它返回了一个引用。 However, if you changed your code to return a value instead, then do_something() would be running on a copy of o1 . 但是,如果您更改代码以返回值,则do_something()将在o1副本上运行。

If you had a third object cls* o_ptr; 如果你有第三个对象cls* o_ptr; and did the following: 并做了以下事情:

cls o1 = 7;
cls o2 = cls(8);
cls* o_ptr = &(o1=o2);

If you displayed o_ptr you'd see it was the same as &o1 if you return a reference, but different if you returned a value. 如果显示o_ptr ,如果返回引用,则会看到它与&o1相同,但如果返回值则不同。

我认为,这个地址是一样的,因为你只是覆盖了结构的内部内容,而不是它在内存中的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM