Accessing class members on a NULL pointer

后端 未结 8 1616
孤城傲影
孤城傲影 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条回答
  •  旧时难觅i
    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.

提交回复
热议问题