C++ Logo

std-proposals

Advanced search

[std-proposals] Calling methods on a nullptr

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Sun, 27 Oct 2024 20:16:40 +0000
This is a totally half-baked idea, but I just want to float it here
sort of like a thought experiment to see if anyone is intrigued by the
possibilities it could open up.

C++ could potentially allow the invocation of a method on a nullptr.
For example:

    class MyClass {
        string name;
    public:
        string GetName(void)
        {
            if ( nullptr == this ) return {};
            return this->name;
        }
    };

It gets a little more complicated if the method is virtual, for example:

    class MyClass {
        string name;
    public:
        virtual string GetName(void)
        {
            if ( nullptr == this ) return {};
            return this->name;
        }
    };

Because if we supply the following standalone function to an x86_64
compiler on Linux:

    string Monkey(MyClass *const p)
    {
        return p->GetName();
    }

It will give us back something like:

    mov r11, rdi # Put the object pointer in R11
    mov r11, [r11] # Put the address of the VTable in R11
    mov r11, [r11] # Put the address of the first method in R11
    jmp r11

This of course will segfault the first time it dereferences R11
because it's a nullptr.

But if we were to mark the class as nullptr-friendly:

    class MyClass friend nullptr {
        string name;
    public:
        virtual string GetName(void)
        {
            if ( nullptr == this ) return {};
            return this->name;
        }
    };

Then our 'Monkey' function would then know to check first whether 'p'
is a nullptr, and if it is a nullptr, then instead of dereferencing
'p' to find a VTable pointer, it instead just uses the VTable of
MyClass.

So it could be possible in the future in C++ to accommodate the
invocation of a method on a nullptr.

Received on 2024-10-27 20:16:49