What will happen when I call a member function on a NULL object pointer?

后端 未结 6 1369
闹比i
闹比i 2020-11-22 01:56

I was given the following as an interview question:

class A
{
public:
    void fun()
    {
        std::cout << "fun" << std::endl;
             


        
6条回答
  •  借酒劲吻你
    2020-11-22 02:51

    By the standard, this is undefined behavior and therefore a very bad thing. In reality of most programming platforms (across both X86 and several other architectures) this will run fine.

    Why? Consider how class functions are implemented in C++. This isn't a virtual function, therefor this can be a static call to a known address. In x86 assembly, we can see this as

    mov A, 0
    mov ecx, A
    call a__fun
    

    since a__fun requires no instance data, even though it receives a null this pointer, nothing will happen.

    Still shitty code and any compiler will scream, but it can run.

提交回复
热议问题