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

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

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

12条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 15:47

    I found another interesting case of explicit usage of the "this" pointer in the Effective C++ book.

    For example, say you have a const function like

      unsigned String::length() const
    

    You don't want to calculate String's length for each call, hence you want to cache it doing something like

      unsigned String::length() const
      {
        if(!lengthInitialized)
        {
          length = strlen(data);
          lengthInitialized = 1;
        }
      }
    

    But this won't compile - you are changing the object in a const function.

    The trick to solve this requires casting this to a non-const this:

      String* const nonConstThis = (String* const) this;
    

    Then, you'll be able to do in above

      nonConstThis->lengthInitialized = 1;
    

提交回复
热议问题