In short, is this undefined behavior?
struct C { int Fn() { return 42; }};
int main() {
C *c = nullptr;
return c->Fn();
}
An important detail is that C::Fn
never does anything with the this
pointer (explicitly or implicitly). I know empirically that some compilers generate code that does exactly what I want in this case but if this tickles UB I can't count on that staying true.
The only related question I've found is this one that would be relevant but for my case not using references.
Edit: this is highly relevant in cases like the following:
void Foo(int len) {
if (len > 1) {
// This can legally be assumed to be dead code;
}
C c;
C* a[2] = {&c, nullptr};
for (int i = 0; i < len ; i++) a[i]->Fn();
}