开发者

C++ function returning value as reference and return *this

开发者 https://www.devze.com 2023-01-16 17:59 出处:网络
if I wanted to return \"this\" from a class member function as reference would this piece of code be correct ?

if I wanted to return "this" from a class member function as reference would this piece of code be correct ?

Record& operator=(const Record& that) {
    m_name = that.m_name;
开发者_StackOverflow社区    return *this;
}

Shouldn't i just use "return this" ?

Thanks for help :)


Yup, that's correct.

Return this wouldn't work since this is a pointer. (The reason it's a pointer and not a reference is because references weren't introduced into the language until after classes.)

In this specific case, if you're just going to assign the members anyway you shouldn't write a copy assignment operator; the default will do the same. When you manage some resource (and invoke the Rule of Three), you'd want to use the copy-and-swap idiom.


Your code is correct, but your comment shouldn't I just use "return this" is wrong (or, more accurately, the answer is "no, you shouldn't, and if you try, any compiler that works even halfway correctly compiler will stop you and give an error message.")

Given a class like:

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

In T::X, this will have the type T *const, and in T::Y, this will have the type T const *const. Either way, it's a pointer to T, not a reference to T. To get a reference to T (for returning or any other purpose) you need to use *this.


It may not matter for this specific case, but it is a good practice to have self assignment guard in the copy-assignment operator.

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

This guards against statements like

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

It would be important when the class is doing some resource (e.g. dynamically allocated memory) management.

0

精彩评论

暂无评论...
验证码 换一张
取 消