Do GCC/Clang allow to access static member through null pointer?

149 views Asked by At
#include <iostream>

struct Foo { static auto foo() -> int { return 123; } };

int main() {
    std::cout << static_cast<Foo*>(nullptr)->foo() << std::endl;
    return 0;
}

I DO KNOW that this is not allowed by standard. But, how about specific compiler?

I only care GCC(G++) and Clang.

Is there any guarantee that these two compiler allow this as compiler feature/specification/extension?

2

There are 2 answers

0
Baum mit Augen On BEST ANSWER

I can find this neither in the list of gcc's C++ extensions nor in the corresponding list for clang. So I would say that you have no guarantee that this works for either compiler.

0
Mats Petersson On

There is nothing saying that this will work. It is up to you, if you decide to use it, to ascertain that it really does work for the actual architecture in which you are using it. And it's important to reflect on the fact that code generation, debug traps for null pointer usage (and such) and optimisation in all compilers is "target system dependent" - so it may well work on x86, but not on MIPS, as an example. Or it may stop working in one way or another in version X+0.0.1 of the compiler.

Having said that, I'd expect this particular example to work perfectly fine on any architecture, because this is not used anywhere.

Note that just because something is undefined, doesn't necessarily mean that it will crash, fail or even "not work exactly as you expect it to". It does, however, allow the compiler to generate whatever code the compiler would like, including something that blows up your computer, formats your hard-drive, etc, etc.