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
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:
Within a member function of a class in C++, does it make a difference, if I use this->dataMember or just dataMember?
Yes, if this is within a class template. Then dataMember
is considered a non-dependent name, which can lead to semantic differences. For example:
#include
int i = 1;
struct R {
int i;
R(): i(2) { }
};
template
struct S: T {
void f() {
std::cout << i << ' ' // selects ::i
<< this->i // selects R::i
<< std::endl;
}
};
int main() {
S().f();
}
What is considered better style?
I don't think that there is a strong opinion within the community about this. Use either style, but be consistent.
Is there any performance difference?
I'm pretty sure there isn't.