Suppose I have a c++ class with a private variable, x. For it’s setter, is there any difference using this? Is there the potential for unwanted / unexpected behavior is I don’t use this?
Setter:
void setX(double input)
{
x = input;
}
Setter using this:
void setX(double x)
{
this->x = x;
}
Because of two-phase lookup for class templates,
thismight be required to(see the first example) Both are equivalent.
In a non-template situation, you usually avoid using
this; the generated code will be the same, thus there won’t be any difference (see the second example).The reason for this is that the compiler will try to lookup every symbol it sees. The first place to lookup is in class-scope (except for block and function scope). If it finds a symbol of that name there, it will emit
thisimplicitly. In reality, member functions are just ordinary functions with an invisible parameter.Is actually transformed into
by the compiler.
Behavioral example for
thisin templates:Output:
Example assembly for non-template:
With
this:Without
this:Verify yourself:
test.cc:
Run
g++ -S test.cc. You’ll see a file namedtest.s, there you can search for the function names.