开发者

When should this-> be used?

I was wondering if this-> should be used both:

void SomeClass::someFunc(int powder)
{
     this->powder = powder;
}

//and
void SomeClass::someFunc(bool enabled)
{
     this->isEnabled = enabled;
}

I'm wondering if the latter is necessary to be proper or if is开发者_Go百科Enabled = enabled would suffice.

Thanks


this->

is needed when using the member directly would be ambiguous. This could happen with template code.

Consider this:

#include <iostream>

template <class T>
class Foo
{
   public:
      Foo() {}
   protected:
      void testing() { std::cout << ":D" << std::endl; }
};

template <class T>
class Bar : public Foo<T>
{
   public:
      void subtest() { testing(); }
};

int main()
{
   Bar<int> bar;
   bar.subtest();
}

This will fail since calling testing() is dependent on a template parameter. To say that you mean the function you will have to do this->testing(); or Foo<T>::testing();

Error message:

temp.cpp: In member function ‘void Bar<T>::subtest()’:
temp.cpp:16:32: error: there are no arguments to ‘testing’ that depend on a template parameter, so a declaration of ‘testing’ must be available [-fpermissive]
temp.cpp:16:32: note: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)


this is just a pointer to the object itself. It is made for readability, so that you know you're referencing to the object functions or variables, not something within the function.

I don't think there's any other good reason for it other than readability :-)

It's also good if you want to avoid ambiguous reference. Assume you have a global variable and a variable within the function that has the same name, then this-> would reference to the global variable.


I think in C++ you leave out the this->, however it's probably personal preference. With or without the code still does the same thing.


I tend to follow this simple rule of thumbs:

  • Attributes: no this, if it's not a parameter of the method, then it's obviously an attribute of the class (and I tend to rely on naming convention anyway to distinguish them)
  • Methods: this->, to distinguish class methods from free-standing functions

The second also brings consistency, since it might be necessary in templated code (and I wrote a lot of it, especially in my pet projects).

The rationale behind this is simple: write as much as necessary to be explicit (ie make the life of your reader easier), but not a stitch more (this would be clutter), which follows Antoine de Saint-Exupery's:

Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜