memory layout C++ objects(内存布局 C++ 对象)
问题描述
我基本上想知道 C++ 如何在内存中布置对象.所以,我听说动态转换只是用偏移量调整内存中对象的指针;和 reinterpret 类型允许我们用这个指针做任何事情.我真的不明白这一点.细节将不胜感激!
I am basically wondering how C++ lays out the object in memory. So, I hear that dynamic casts simply adjust the object's pointer in memory with an offset; and reinterpret kind of allows us to do anything with this pointer. I don't really understand this. Details would be appreciated!
推荐答案
每个类都按照声明的顺序排列其数据成员.
允许编译器在成员之间放置填充以提高访问效率(但不允许重新排序).
Each class lays out its data members in the order of declaration.
The compiler is allowed to place padding between members to make access efficient (but it is not allowed to re-order).
dynamic_cast<>
的工作原理是编译器实现细节,标准中没有定义.这完全取决于编译器使用的 ABI.
How dynamic_cast<>
works is a compiler implementation detail and not defined by the standard. It will all depend on the ABI used by the compiler.
reinterpret_cast<>
只需更改对象的类型即可.您唯一可以保证有效的是,将指向 void* 的指针转换为指向 class 的指针将返回相同的指针.
reinterpret_cast<>
works by just changing the type of the object. The only thing that you can guarantee that works is that casting a pointer to a void* and back to the same the pointer to class will give you the same pointer.
这篇关于内存布局 C++ 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:内存布局 C++ 对象
- 近似搜索的工作原理 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 从python回调到c++的选项 2022-11-16
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01