Agreed, one of the biggest design mistakes in the OOP syntax of C++ (and Java, for that matter) was not making `this` mandatory when referring to instance members.
(- this->b + sqrt(this->b * this->b - 4 this->a * this->c))/(2 * this->a)
and (- this->b - sqrt(this->b * this->b - 4 this->a * this->c))/(2 * this->a)
This is a readability problem for any class that is used to do computations.What I don’t like is being able to reference instance members without `this`, e.g.
void foo() {
int x = bar + 1; // should be illegal: it can be hard to distinguish if `bar` is a local variable versus an instance member
int y = this->bar + 1; // disambiguation is good
}If it was this->bar it could be a member, it could also be a static variable. A bar on its own could be local or it could be in any of the enclosing scopes or namespaces. Forcing "this" to be explicit doesn't make the code any clearer on its own.
#include <iostream>
struct Foo {
void bar() {
std::cout << this << std::endl;
}
};
int main() {
Foo *p = nullptr;
p->bar();
}
will print 0I wouldn't be surprised if any null check against this would be erased by the optimizer for example as the parent comment mentioned. Sanitizers might check for null this too.
Foo *p = nullptr;
p->bar();
That's undefined behavior. It's "allowed" in the sense of "yes it's possible to write, compile and run that code", but the language makes no guarantees about what the results will be. So maybe not the most useful definition of "allowed". /app/example.cpp:10:6: runtime error: member call on null pointer of type 'Foo'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /app/example.cpp:10:6
/app/example.cpp:3:8: runtime error: member call on null pointer of type 'Foo *'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /app/example.cpp:3:8That would be a complete redability disaster... at least for C++. Java peeps probably won't even flinch ;)