Are there any reasons I shouldn't do this?
Yes, there is a reason why you shouldn't do this.
Referencing a member variable with this->
is strictly required only when a name has been hidden, such as with:
class Foo
{
public:
void bang(int val);
int val;
};
void Foo::bang(int val)
{
val = val;
}
int main()
{
Foo foo;
foo.val = 42;
foo.bang(84);
cout << foo.val;
}
The output of this program is 42
, not 84
, because in bang
the member variable has been hidden, and val = val
results in a no-op. In this case, this->
is required:
void Foo::bang(int val)
{
this->val = val;
}
In other cases, using this->
has no effect, so it is not needed.
That, in itself, is not a reason not to use this->
. The maintennance of such a program is however a reason not to use this->
.
You are using this->
as a means of documentation to specify that the vairable that follows is a member variable. However, to most programmers, that's not what usign this->
actually documents. What using this->
documents is:
There is a name that's been hidden here, so I'm using a special
technique to work around that.
Since that's not what you wanted to convey, your documentation is broken.
Instead of using this->
to document that a name is a member variable, use a rational naming scheme consistently where member variables and method parameters can never be the same.
Edit Consider another illustration of the same idea.
Suppose in my codebase, you found this:
int main()
{
int(*fn)(int) = pingpong;
(fn)(42);
}
Quite an unusual construct, but being a skilled C++ programmer, you see what's happening here. fn
is a pointer-to-function, and being assigned the value of pingpong
, whatever that is. And then the function pointed to by pingpong
is being called with the singe int
value 42
. So, wondering why in the world you need such a gizmo, you go looking for pingpong
and find this:
static int(*pingpong)(int) = bangbang;
Ok, so what's bangbang
?
int bangbang(int val)
{
cout << val;
return val+1;
}
"Now, wait a sec. What in the world is going on here? Why do we need to create a pointer-to-function and then call through that? Why not just call the function? Isn't this the same?"
int main()
{
bangbang(42);
}
Yes, it is the same. The observable effects are the same.
Wondering if that's really all there is too it, you see:
/* IMPLEMENTATION NOTE
*
* I use pointers-to-function to call free functions
* to document the difference between free functions
* and member functions.
*/
So the only reason we're using the pointer-to-function is to show that the function being called is a free function
and not a member function.
Does that seem like just a "matter of style" to you? Because it seems like insanity to me.