When should you use the "this" keyword in C++?

c++, coding-style

Solution

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.

Problem

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?

Original source

Related problems