Possible Duplicates:
Is excessive use of this in C++ a code smell
Years ago, I got in the habit of using this-> when accessing member variables. I knew it wasn't strictly necessary, but I thought it was more clear.
Then, at some point, I started to prefer a more minimalistic style and stopped this practice...
Recently I was asked by one of my more junior peers whether I thought it was a good idea and I found that I didn't really have a good answer for my preference... Is this really a wholly stylistic choice or are there real reasons why not prefixing this-> on member variable accesses is better?
The this keyword refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method.
Yes, you can.
While this is a totally subjective question, I think the general C++ community prefers not to have this-> . Its cluttering, and entirely not needed. Some people use it to differentiate between member variables and parameters.
The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).
While this is a totally subjective question, I think the general C++ community prefers not to have this->
. Its cluttering, and entirely not needed.
Some people use it to differentiate between member variables and parameters. A much more common practice is to just prefix your member variables with something, like a single underscore or an m
, or m_
, etc.
That is much easier to read, in my opinion. If you need this->
to differentiate between variables, you're doing it wrong. Either change the parameter name (from x
to newX
) or have a member variable naming convention.
Consistency is preferred, so instead of forcing this->
on yourself for the few cases you need to differentiate (note in initializer lists this is completely well-defined: x(x)
, where the member x
is initialized by the parameter x
), just get better variable names.
This leaves the only time I use this
: when I actually need the address of the instance, for whatever reason.
I can only recall doing it with
delete this;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With