Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean std::swap(*(void **)x, *(void **)y)?

Tags:

c++

I just read this answer How are virtual functions and vtable implemented?. The author of the response uses this expression:

std::swap(*(void **)x, *(void **)y);
// Now x is a C, and y is a B! Hope they used the same layout of members!

Somebody could explain how does it work? Why and what does mean (void **) followed by the operator*?

like image 312
Thomas Avatar asked Feb 07 '23 15:02

Thomas


1 Answers

It involves undefined behavior, and so it's not guaranteed to work.

The basic idea is that x and y are pointers that point to objects of the same base type, where that type has at least one virtual function, and where the compiler has implemented the virtual function mechanism by placing a vtable pointer at the very start of each object (i.e. at offset 0). This is the by far most common way to do things. But not the only way.

The swap then assumes that these vtable pointers are the same size as void*.

like image 137
Cheers and hth. - Alf Avatar answered Feb 25 '23 01:02

Cheers and hth. - Alf