Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance penalties on using "this->"?

Tags:

c++

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


2 Answers

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

like image 147
Seth Carnegie Avatar answered Aug 01 '26 07:08

Seth Carnegie


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.

like image 27
Jerry Coffin Avatar answered Aug 01 '26 08:08

Jerry Coffin