Consider this example of two similar C++ member functions in a class C:
void C::function(Foo new_f) {
f = new_f;
}
and
void C::function(Foo new_f) {
this->f = new_f;
}
Are these functions compiled in the same manner? Are there any performance penalties for using this-> (more memory accesses or whatever)?
Yes, it's exactly the same and you'll get the same performance.
The only time you really must use the this-> syntax is when you have an argument to the function with the same name as an instance variable you want to access. Using the name of the variable by itself will refer to the argument so you need the this->. Of course, you could just rename the argument too. And, as ildjarn has pointed out in the comments also, you need to use this in certain situations to call functions that are dependent because this is implicitly dependent (you can read more about that though).
From the viewpoint of the compiler, there's no difference between this-> being implicit and being explicit.
Remember, however, that code should be written primarily for human readers, and only secondarily for the compiler. From this viewpoint, using this-> (except in the few places it's truly needed) is a huge loss, and should be expunged from all code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With