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

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?


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;

Personally I never use this, except:

  • when I need to pass 'this' as an argument to a method of another class
  • in the implementation of the assignment operator

When there is an ambiguity between, say, a function parameter and an instance variable.

Of course such ambiguity should be avoided! It might be preferable to change the function parameter name instead of incurring overhead (i.e. prefixes) for all access to instance parameters though...


It's usable when you have variables in a scope "above" the one you are working with.

int i;
public void foo() {
    int i;
    i = 3; // assign local variable
    this->i = 4; // assign global variable
}

Other than accessing variables in another scope, I myself agree with your "minimalistic choice". Less is more. :-)