3 ms·
that's not really true - unlike a regular pointer, `this` is not allowed to be null, thus removing `if(this == nullptr)` is always a valid optimization to do.
by jcelerier 1y ago
that's not really true - unlike a regular pointer, `this` is not allowed to be null, thus removing `if(this == nullptr)` is always a valid optimization to do.
- hhdknddkkjd 1y agoOnly in so much that this being null is UB, but in the real world it very much can be null and programs will sometimes crash deep inside methods called on nullptr.
- cherryteastain 1y agoIt absolutely is allowed to be null: #include <iostream> struct Foo { void bar() { std::cout << this << std::endl; } }; int main() { Foo *p = nullptr; p->bar(); } will print 0
- Krssst 1y agoThis is undefined behavior in my understanding, it just happens to work until it doesn't. I 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.
- usefulcat 1y agoFoo *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".
- steveklabnik 1y agoJust to cite what the others have told you: https://godbolt.org/z/bWfaYrqoY https://godbolt.org/z/bWfaYrqoY /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:8
- jcelerier 1y agoThat code is outside the set of valid c++ programs
- deleted 1y ago[deleted]