赋值运算符在C ++中返回对* this的引用 [英] assignment operator return a reference to *this in C++

查看:154
本文介绍了赋值运算符在C ++中返回对* this的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Effective c ++中读到这个,这是Col.10。
它说这是一个好的方法让赋值运算符返回一个引用* this。
我写了一个代码片段来测试这个想法。我覆盖了赋值操作符这里。并测试了它。一切安好。
但是当我删除该操作符覆盖,一切都是一样的。这意味着,链接分配仍然工作良好。那么,我错过了什么?这是为什么?需要一些解释,谢谢你。

I read about this from "Effective c++" ,this is Col.10. It say it's a good way to have assignment operators return a reference to *this. I wrote a code snippet to test this idea. I overridden the assignment operator here.And tested it. Everything is fine. But when I remove that operator overriding, everything is the same. That means, the chaining assignment still works well. So, what am I missing? Why is that? Need some explanation from you guys, THank you.

#include <iostream>

using namespace std;

class Widget{
public:

    Widget& operator=(int rhs)
    {
        return *this;
    }
    int value;

};

int main()
{
    Widget mywidget;
    mywidget.value = 1;
    Widget mywidget2;
    mywidget2.value = 2;
    Widget mywidget3 ;
    mywidget3.value = 3;
    mywidget = mywidget2 = mywidget3;
    cout << mywidget.value<<endl;
    cout << mywidget2.value<<endl;
    cout << mywidget3.value<<endl;

}


推荐答案

完全删除 operator = 方法,编译器将创建一个默认的 operator = > 1 ,并返回对 * this 的引用。

If you remove completely the operator= method, a default operator= will be created by the compiler, which implements shallow copy1 and returns a reference to *this.

>

Incidentally, when you write

mywidget = mywidget2 = mywidget3;

你实际上是调用这个默认 operator = ,因为您的重载运算符设计为在右侧使用 int

you're actually calling this default operator=, since your overloaded operator is designed to work with ints on the right side.

停止工作,而是如果你返回一个值,一个 const 引用(=>你会得到编译错误)或引用不同于<$

The chained assignment will stop working, instead, if you return, for example, a value, a const reference (=>you'll get compilation errors) or a reference to something different from *this (counterintuitive stuff will start to happen).

部分相关:复制和交换习语,即写一个赋值运算符的完美方式。强烈建议阅读,如果您需要写一个 operator =

Partially related: the copy and swap idiom, i.e. the perfect way to write an assignment operator. Strongly advised read if you need to write an operator=


  1. 默认的 operator = 将执行,就好像左手操作数的每个成员和右手一。这意味着对于原始类型,它将是一个残酷的按位复制,在90%的情况下,不能确定指向所拥有的资源。

  1. The default operator= will perform as if there were an assignment between each member of the left hand operand and each member of the right hand one. This means that for primitive types it will be a "brutal" bitwise copy, which in 90% of cases isn't ok for pointers to owned resources.

这篇关于赋值运算符在C ++中返回对* this的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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