Within a member function of a class in C++, does it make a difference, if I use this->dataMember
or just dataMember
? What is considered better style? Is there any performance difference?
(I am not talking about the case where a local variable has the same name as the data member, in which case you must, to my knowledge, use this->
to distinguish between them.)
use this when you have a hidden/private member =) in any other case it does not make a difference =)
from the IBM information center i quote the following
it's simply redundant to use
this->
to call members, unless you want to semantically distinguish between locals and members quickly. a lot of people use them_
prefix for class members, to avoid writingthis->
all the time.I always use
this
when calling member functions.self
is mandatory, so it's not a real burden for me.But for data members I use it only when necessary because there is no ADL taking place. To answer your specific questions:
Yes, if this is within a class template. Then
dataMember
is considered a non-dependent name, which can lead to semantic differences. For example:I don't think that there is a strong opinion within the community about this. Use either style, but be consistent.
I'm pretty sure there isn't.
This is a matter of style. Some people like the extra
this->
to make it more obvious that you are accessing a class member. But if you feel it's obvious enough without it, there will be no difference in the generated code or performance.(Besides the case you mentioned with overlapping scopes,
this->
can also be mandatory in a template when trying to name a member of a type-dependent base class.)As a general rule, it's a question of local conventions. Most of the places I've seen do not use
this->
except when necessary, and that's the convention I prefer as well, but I've heard of people who prefer to use it systematically.There are two cases when it is necessary. The first is if you've hidden the name with the same name in local scope; if e.g. you have a member named
toto
, and you also named your function argumenttoto
. Many coding conventions mark either the member or argments to avoid this case, e.g. all member names start withmy
orm_
, or a parameter name will start withthe
.The other case is that
this->
can be used in a template to make a name dependent. This is relevant if a template class inherits from a dependent type, and you want to access a member of the base, e.g.:Without the
this->
here,g()
would be a non-dependent name, and the compiler would look it up in the context of the template definition, without taking the base class into consideration.using "this->" is better (you are sure it's the members) but it's doesn't make a difference