gpt4 book ai didi

c++ - POD 结构(相同类型的成员): are members in contiguous memory locations?

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

给定

template <typename T>
struct Vector3d { T x, y, z; };
  • 假设 x、y 和 z 位于连续的内存位置是否安全?

  • 对于 T = floatT = double 至少可以安全地假设吗?

  • 如果不能,是否有可能以跨平台的方式实现?

注意:只要 x、y、z 是连续的,我不介意在 z 之后填充

最佳答案

Is it safe to assume that x, y, and z are in contiguous memory locations?

从技术上讲,语言没有这样的保证。

另一方面,它们也没有必要不连续,实际上它们很可能是连续的。

If not is it possible to enforce in a cross-platform way?

确保对象位于连续内存位置的跨平台方式是数组:

template <typename T>
struct Vector3d { T components[3]; };

数组还使使用指针算法迭代对象成为合法的。

关于c++ - POD 结构(相同类型的成员): are members in contiguous memory locations?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57808669/

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