C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Caching the offset for dynamic_cast

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Thu, 11 Jul 2024 08:34:32 +0100
On Wed, Jul 10, 2024 at 15:33 PM Thiago wrote:
>>
>> if ( typeid(*p) == typeid(MostDerived) ) pd = p + offset;
>> else if ( typeid(*p) == typeid(MostDerived2) ) pd = p + offset2;
>> else if ( typeid(*p) == typeid(MostDerived3) ) pd = p + offset3;
>> else pd = dynamic_cast<Derived*>(p);
>
> You can just use static_cast there.


I wasn't sure at first so I wrote the following small program:

    #include <new>

    struct Base { virtual ~Base(void) = default; };

    struct Derived : Base {
        char buf[1024u];
        void Wipe(void) { ::new(buf) char[1024u]{}; }
    };

    void Bad_Function(Base *const p)
    {
        Derived *pd = static_cast<Derived*>(p);
        pd->Wipe();
    }

    int main(void)
    {
        Base var;
        Bad_Function(&var);
    }

This program successfully compiles, and as expected, segfaults. I've
never seen 'static_cast' used to perform a downcast like that, and I
didn't realise it had this functionality. I wonder who thought that
this would be a good feature? 'static_cast' should not be able to do
stuff like this. 'static_cast' should be a much weaker cast than this,
to do simple things such as making an implicit conversion explicit...
it shouldn't be able to cast to a different type that results in the
calling of a method that segfaults.

Would anyone agree with me that this functionality should be taken
away from 'static_cast'? i.e. deprecated in C++26 and removed in
C++29. It could be replaced with a standard library function
"std::explicit_down_cast".

Received on 2024-07-11 07:34:44