Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 423
dicroce Avatar asked Feb 25 '10 20:02

dicroce


People also ask

What is the this keyword in C?

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.

Can you use keyword this in C?

Yes, you can.

Should you use this -> in C++?

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.

What is the use of this keyword?

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).


2 Answers

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.

like image 181
GManNickG Avatar answered Sep 22 '22 08:09

GManNickG


I can only recall doing it with

delete this; 
like image 32
Tim Avatar answered Sep 23 '22 08:09

Tim