Should I use `this` within a class?

前端 未结 7 1638
小蘑菇
小蘑菇 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:33

    I always use this when calling member functions.

    1. It turns the function name into a dependent name so that base class member functions are found within a class template.
    2. It suppresses argument-dependent lookup. ADL has its advantages, but it can lead to surprising behavior, and I like it if it's not getting in my way.
    3. It has no real disadvantages, and so I use it for all member function calls for consistency reasons.
    4. I program in Python a lot where an explicit self is mandatory, so it's not a real burden for me.

    But for data members I use it only when necessary because there is no ADL taking place. To answer your specific questions:

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

    Yes, if this is within a class template. Then dataMember is considered a non-dependent name, which can lead to semantic differences. For example:

    #include 
    
    int i = 1;
    
    struct R {
      int i;
      R(): i(2) { }
    };
    
    template
    struct S: T {
      void f() {
        std::cout << i << ' '     // selects ::i
                  << this->i      // selects R::i
                  << std::endl;
      }
    };
    
    int main() {
      S().f();
    }
    

    What is considered better style?

    I don't think that there is a strong opinion within the community about this. Use either style, but be consistent.

    Is there any performance difference?

    I'm pretty sure there isn't.

提交回复
热议问题