When should I make explicit use of the `this` pointer?

后端 未结 12 1345
甜味超标
甜味超标 2020-11-22 15:19

When should I explicitly write this->member in a method of a class?

12条回答
  •  青春惊慌失措
    2020-11-22 15:51

    One other case is when invoking operators. E.g. instead of

    bool Type::operator!=(const Type& rhs)
    {
        return !operator==(rhs);
    }
    

    you can say

    bool Type::operator!=(const Type& rhs)
    {
        return !(*this == rhs);
    }
    

    Which might be more readable. Another example is the copy-and-swap:

    Type& Type::operator=(const Type& rhs)
    {
        Type temp(rhs);
        temp.swap(*this);
    }
    

    I don't know why it's not written swap(temp) but this seems to be common.

提交回复
热议问题