Accessing class members on a NULL pointer

后端 未结 8 1603
孤城傲影
孤城傲影 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 14:55

    In the original days of C++, the C++ code was converted to C. Object methods are converted to non-object methods like this (in your case):

    foo_say_hi(Foo* thisPtr, /* other args */) 
    {
    }
    

    Of course, the name foo_say_hi is simplified. For more details, look up C++ name mangling.

    As you can see, if the thisPtr is never dereferenced, then the code is fine and succeeds. In your case, no instance variables or anything that depends on the thisPtr was used.

    However, virtual functions are different. There's a lot of object lookups to make sure the right object pointer is passed as the paramter to the function. This will dereference the thisPtr and cause the exception.

提交回复
热议问题