Accessing class members on a NULL pointer

后端 未结 8 1298
孤城傲影
孤城傲影 2020-11-22 14:11

I was experimenting with C++ and found the below code as very strange.

class Foo{
public:
    virtual void say_virtual_hi(){
        std::cout << \"Vi         


        
相关标签:
8条回答
  • 2020-11-22 15:14

    The call to say_hi is statically bound. So the computer actually simply does a standard call to a function. The function doesn't use any fields, so there is no problem.

    The call to virtual_say_hi is dynamically bound, so the processor goes to the virtual table, and since there is no virtual table there, it jumps somewhere random and crashes the program.

    0 讨论(0)
  • 2020-11-22 15:14

    It's important to realize that both calls produce undefined behavior, and that behavior may manifest in unexpected ways. Even if the call appears to work, it may be laying down a minefield.

    Consider this small change to your example:

    Foo* foo = 0;
    foo->say_hi(); // appears to work
    if (foo != 0)
        foo->say_virtual_hi(); // why does it still crash?
    

    Since the first call to foo enables undefined behavior if foo is null, the compiler is now free to assume that foo is not null. That makes the if (foo != 0) redundant, and the compiler can optimize it out! You might think this is a very senseless optimization, but the compiler writers have been getting very aggressive, and something like this has happened in actual code.

    0 讨论(0)
提交回复
热议问题