Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 它是什么意思std::swap(*(void**)x,*(void**)y)?_C++ - Fatal编程技术网

C++ 它是什么意思std::swap(*(void**)x,*(void**)y)?

C++ 它是什么意思std::swap(*(void**)x,*(void**)y)?,c++,C++,我刚刚读了这个答案。响应的作者使用以下表达式: std::swap(*(void **)x, *(void **)y); // Now x is a C, and y is a B! Hope they used the same layout of members! 有人能解释它是怎么工作的吗?为什么和什么是(void**),后面跟着操作符*?它涉及未定义的行为,因此不能保证工作 基本思想是x和y是指向相同基本类型的对象的指针,其中该类型至少有一个虚拟函数,并且编译器通过在每个对象的最开始处

我刚刚读了这个答案。响应的作者使用以下表达式:

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

有人能解释它是怎么工作的吗?为什么和什么是
(void**)
,后面跟着
操作符*

它涉及未定义的行为,因此不能保证工作

基本思想是
x
y
是指向相同基本类型的对象的指针,其中该类型至少有一个虚拟函数,并且编译器通过在每个对象的最开始处(即偏移量0处)放置一个vtable指针来实现虚拟函数机制。这是迄今为止最常见的做事方式。但这不是唯一的办法


然后,交换假设这些vtable指针的大小与
void*

相同,这不好。可能对你有帮助。这也是一种严格的别名冲突