3 ms·
Why is that undefined? Seems like it should obviously cause a fault...
by MichaelGG 12y ago
Why is that undefined? Seems like it should obviously cause a fault...
- pcwalton 12y agoC and C++ need to be usable in systems without memory protection, so they don't guarantee any faults for operations like method calls. (There are some standard-guaranteed exceptions, for example std::bad_alloc, but those are only on relatively expensive operations.) Compilers then take advantage of these undefined behaviors to optimize even on systems that do have memory protection.
- kevinnk 12y agoIt's an optimization. Virtual methods that don't dereference this (by not accessing any non static member variables for example) don't have to check if this is null. For example, class Example { public: static bool do_it; virtual void do_it_if() { if (g_do_it) return; /* otherwise do something that dereferences this... */ } }; void test1() { Example::do_it = false; static_cast<Example *>(NULL)->do_it_if(); } void test2() { Example::do_it = true; static_cast<Example *>(NULL)->do_it_if(); } In the above code, only test2 crashes (clang 6.0). If crashing was defined behavior you would need an extra check in the code generated for do_it_if. EDIT: Also, it's worth explaining why test1 works even though do_it_if is virtual. Since there aren't any methods that override do_it_if, the virtual method lookup can be elided and you don't have to dereference this to find the vtable. If do_it_if had been overridden and the runtime type was unknown, you would need to dereference this to lookup do_it_if in the vtable, which would segfault in both tests.