Monday, April 23, 2012

How can C++ compiler optimize incorrect hierarchical downcast to cause real undefined behavior

Consider the following example:



class Base {
public:
int data_;
};

class Derived : public Base {
public:
void fun() { ::std::cout << "Hi, I'm " << this << ::std::endl; }
};

int main() {
Base base;
Derived *derived = static_cast<Derived*>(&base);

derived->fun(); // Undefined behavior!

return 0;
}


Function call is obviously undefined behavior according to C++ standard. But on all available machines and compilers (VC2005/2008, gcc on RH Linux and SunOS) it works as expected (prints "Hi!"). Do anyone know configuration this code can work incorrectly on? Or may be, more complicated example with the same idea (note, that Derived shouldn't carry any additional data anyway)?



Thanks,
Mike.





No comments:

Post a Comment