C++ Logo

std-proposals

Advanced search

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

From: Rhidian De Wit <rhidiandewit_at_[hidden]>
Date: Thu, 11 Jul 2024 11:56:58 +0200
static_cast cannot convert types to a different type that don't share a
relation. A base -> derived is a valid downcast, but it's up to the
programmer to ensure that the downcast is safe. If you're not sure about
the downcast, use dynamic_cast.

This is perfectly defined and has been around for ages, I don't think it
should be changed.

Op do 11 jul 2024 om 09:34 schreef Frederick Virchanza Gotham via
Std-Proposals <std-proposals_at_[hidden]>:

> 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".
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>


-- 
Rhidian De Wit
Software Engineer - Barco

Received on 2024-07-11 09:57:13