In C++, the T q = dynamic_cast construction performs a runtime cast of a pointer p to some other pointer type T that must
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