Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "switch and op code" in the context of type-erasure and/or just std::function?

I watched C++ Type Erasure Demystified - Fedor G Pikus - C++Now 2024, and at 21:07 somebody from the audience mentions, I think, "switch and op code", claiming "that's how std::function works", and Pikus seems to know what that they guy is talking about.

But I don't.

What's that? Can somebody provide an explanation of what technique/pattern/idiom "swith and op code" is, the motivations for it, and an example of how it can be used?

(I'm wildly guessing that "switch" refers to switch-statement.)

like image 735
Enlico Avatar asked Oct 29 '25 10:10

Enlico


1 Answers

I think it came up in one conference but i don't recall which, will post it when i find it.

If you have 3 functions you can store 3 function pointers, which will take 24 bytes on x64 system.

struct s
{
    void(*call_f)(void*);
    void(*copy_f)(void*);
    void(*destruct_f)(void*);
};

You can instead store one function pointer that expects an op-code

enum op_code : char
{
    call_f,
    copy_f,
    destruct_f
};

struct s
{
    void(*united_call)(void*, op_code);
};

Inside this united_call , you can switch over the op-code

void united_call_ex(void* ptr, op_code code)
{
    switch(code)
    {
        case call_f:
          call_function(ptr);
          break;
        case copy_f:
          copy_function(ptr);
          break;
        case destruct_f:
          destruct_function(ptr);
          break;
    }
}

This implementation could reduce the size of std::function, but it has an extra decision that needs to be made at runtime, and implementing the call operator would be harder, because it cannot return (you will have to pass a pointer to a properly aligned buffer that you move the result into, which adds extra operations), so maybe only use it for the copy construct, and delete operations.

It is used in libstdc++ for the copy and destruct, while libc++ seems to use a vtable for the copy and destruct instead, and MSVC stores all the operations in the object itself.

like image 102
Ahmed AEK Avatar answered Oct 31 '25 00:10

Ahmed AEK