Are there practical uses for dynamic-casting to void pointer?

后端 未结 7 1305
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 14:00

In C++, the T q = dynamic_cast(p); construction performs a runtime cast of a pointer p to some other pointer type T that must

7条回答
  •  广开言路
    2020-11-27 14:32

    Expanding on @BruceAdi's answer and inspired by this discussion, here's a polymorphic situation which may require pointer adjustment. Suppose we have this factory-type setup:

    struct Base { virtual ~Base() = default; /* ... */ };
    struct Derived : Base { /* ... */ };
    
    template 
    Base * Factory(Args &&... args)
    {
        return ::new Derived(std::forward(args)...);
    }
    
    template 
    Base * InplaceFactory(void * location, Args &&... args)
    {
        return ::new (location) Derived(std::forward(args)...);
    }
    

    Now I could say:

    Base * p = Factory();
    

    But how would I clean this up manually? I need the actual memory address to call ::operator delete:

    void * addr = dynamic_cast(p);
    
    p->~Base();              // OK thanks to virtual destructor
    
    // ::operator delete(p); // Error, wrong address!
    
    ::operator delete(addr); // OK
    

    Or I could re-use the memory:

    void * addr = dynamic_cast(p);
    p->~Base();
    p = InplaceFactory(addr, "some", "arguments");
    
    delete p;  // OK now
    

提交回复
热议问题