代码之家  ›  专栏  ›  技术社区  ›  Sebastian Dusza

函数返回值作为参考并返回*

c++
  •  3
  • Sebastian Dusza  · 技术社区  · 14 年前

    如果我想从类成员函数返回“this”作为引用,这段代码是否正确?

    Record& operator=(const Record& that) {
        m_name = that.m_name;
        return *this;
    }
    

    我不应该用“还这个”吗?

    感谢您的帮助:)

    3 回复  |  直到 14 年前
        1
  •  8
  •   GManNickG    14 年前

    是的,没错。

    返回 this 从那以后就不行了 是指针。(之所以是指针而不是引用,是因为直到下课后才将引用引入语言。)

    在这种特定的情况下,如果您只是要分配成员,则不应编写复制分配运算符;默认情况下也会这样做。当您管理一些资源(并调用 Rule of Three ,您将要使用 copy-and-swap idiom .

        2
  •  4
  •   Jerry Coffin    14 年前

    您的代码是正确的,但是您的注释 shouldn't I just use "return this" 是错误的(或者更准确地说,答案是“不,你不应该这样做,如果你尝试过,任何一个运行正常的编译器都会阻止你并给出错误消息。”)

    给一个类,比如:

    class T { 
        void X() {}
        void Y() const {}
    };
    

    T::X , this 将具有类型 T *const ,和 T::Y , 将具有类型 T const *const . 不管怎样,这是一个 指针 对T,而不是A 参考 to t.要获得t的引用(用于返回或任何其他目的),您需要使用 *this .

        3
  •  1
  •   Arun    14 年前

    对于这种特定的情况,这可能无关紧要,但在副本分配操作符中设置自分配保护是一种良好的做法。

    Record& operator=(const Record& that) {
        if( &that != this ) {
            m_name = that.m_name;
        }
        return *this;
    }
    

    这是为了防止像

    Record r;
    // do something with r
    r = r;     // this is protected
    

    当类正在执行某些资源(例如动态分配的内存)管理时,这一点很重要。