27

5.2.7/7 says something along the lines of:

If T is "pointer to cv void", the result is a pointer to the most derived class pointed to by x.

What is a good application of this syntax? When should dynamic_cast<void*> be used?

Evg
  • 25,259
  • 5
  • 41
  • 83
David G
  • 94,763
  • 41
  • 167
  • 253
  • Here's an example of what MSalters is describing: http://ideone.com/84U5ax – Vaughn Cato Sep 01 '14 at 18:36
  • I think allocators can make use of this (memory management). E.g. if you need the starting address of a block of memory, but you only have a pointer to a base class. – dyp Sep 01 '14 at 20:05
  • @dyp: If you already have an object, its memory must already be allocated, so an allocator can't allocate that again. And for deallocation you need more than just the base address, you need the most derived type so you can run all destructors. – MSalters Sep 01 '14 at 20:15
  • @MSalters If your destructor is virtual you don't need the most derived type, and if it isn't virtual it's your own fault and you are screwed anyway. – n. m. could be an AI Sep 01 '14 at 20:50

2 Answers2

28

One common reason is to figure out whether two interfaces IA* and IB* are in fact pointers to the same underlying object. If you need that, use the cast.

IIRC, it's even possible in case of Multiple Inheritance with a repeated non-virtual base to have two IA* pointers which compare unequal, yet point to the same object - because they point to two different IA subobjects.

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • 1
    I don't understand what is the difference between `dynamic_cast(ptr)` and `static_cast(ptr)` (since `void*` does not have any RTTI or vtable).... – Basile Starynkevitch Sep 01 '14 at 17:44
  • @BasileStarynkevitch `ptr` is a pointer to class type, so it can have RTTI. – Oktalist Sep 01 '14 at 19:29
  • So what, `void*` is a generic pointer so don't have any RTTI, IMHO. – Basile Starynkevitch Sep 01 '14 at 19:31
  • 2
    @BasileStarynkevitch: That prevents the cast _back_ to the original type. And to address your first comment, a `static_cast` may give you a pointer to a base class somewhere in the middle of the full object, which may not be unique. – MSalters Sep 01 '14 at 20:13
6

When you have something like:

template<typename X, typename Y>
bool operator==(const X* px, const Y* py) {
     return dynamic_cast<void*>(px) == dynamic_cast<void*>(py);
}
Pradhan
  • 16,391
  • 3
  • 44
  • 59
Paul Evans
  • 27,315
  • 3
  • 37
  • 54