C ++ function returns value as a reference and returns * this

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

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

Should I just use "return this"?

Thanks for the help:)

+3
source share
3 answers

Yup, that's right.

Return thiswill not work as it thisis a pointer. (The reason this is a pointer and not a link is because the links were not entered into the language until the classes were gone.)

, , ; . ( 3), .

+8

, shouldn't I just use "return this" (, , "", , , , , . ")

:

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

T::X, this T *const, T::Y, this T const *const. , T, T. T ( ), *this.

+4

In this particular case, this may not be important, but there is a good practice in the copy-destination operator to have a protective self-start mechanism.

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

This protects against claims such as

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

It would be important when a class performs resource management (for example, dynamically allocated memory).

+1
source

Source: https://habr.com/ru/post/1765683/


All Articles