gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:22:29 27 4
gpt4 key购买 nike

我刚读了这个答案How are virtual functions and vtable implemented? .响应的作者使用了这个表达式:

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 **) 后跟 operator*

最佳答案

它涉及未定义的行为,因此不能保证有效。

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

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

关于c++ - std::swap(*(void **)x, *(void **)y) 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35690573/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com