Should I use `this` within a class?

前端 未结 7 1634
小蘑菇
小蘑菇 2020-12-14 07:20

Within a member function of a class in C++, does it make a difference, if I use this->dataMember or just dataMember? What is considered better

相关标签:
7条回答
  • 2020-12-14 07:44

    As a general rule, it's a question of local conventions. Most of the places I've seen do not use this-> except when necessary, and that's the convention I prefer as well, but I've heard of people who prefer to use it systematically.

    There are two cases when it is necessary. The first is if you've hidden the name with the same name in local scope; if e.g. you have a member named toto, and you also named your function argument toto. Many coding conventions mark either the member or argments to avoid this case, e.g. all member names start with my or m_, or a parameter name will start with the.

    The other case is that this-> can be used in a template to make a name dependent. This is relevant if a template class inherits from a dependent type, and you want to access a member of the base, e.g.:

    template <typename T>
    class Toto : public T
    {
    public:
        int f()
        {
            return this->g();
        }
    };
    

    Without the this-> here, g() would be a non-dependent name, and the compiler would look it up in the context of the template definition, without taking the base class into consideration.

    0 讨论(0)
提交回复
热议问题