c++ - 类变量 - 对齐

标签 c++ operators

<分区>

Possible Duplicate:
Classes store data members in sequential memory?

只是想问一下为什么以下是正确的:

template<class T>
class Vec3 {
public:
  // values
  T x,y,z;

  // returns i-th komponent (i=0,1,2) (RHS array operator)
  const T operator[] (unsigned int i) const {
    return *(&x+i);
  }
}

或者换句话说:为什么总是保证 x, y 和 z 在内存中总是相隔 sizeof(T) 个单位。这些变量中的两个之间不能有碎片漏洞,从而让这个运算符返回一个假值吗?

最佳答案

保证xyz总是sizeof(T) 单元在内存中分开。中间可以添加填充字节。
它作为实现细节被遗漏了。
唯一可以保证的是,类/结构的开头与其 POD 结构/类的第一个成员之间没有填充。

不保证您的代码中 operator[] 的实现总是有效。

引用:
C++11: 9.2 类成员 [class.mem]

14) Nonstatic data members of a (non-union) class with the same access control (Clause 11) are allocated so that later members have higher addresses within a class object. The order of allocation of non-static data members with different access control is unspecified (11). Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so might requirements for space for managing virtual functions (10.3) and virtual base classes (10.1).

关于c++ - 类变量 - 对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14361006/

相关文章:

php - PHP 中的 'as' 运算符

php - SQL 运算符 : AND and OR

c++ - Code::Blocks 控制台应用程序不会显示输出

c# - 使用 C++ dll 函数提高 C# 项目的性能

c++ - 为什么我们不能接受输入并一步操作它?

C# 0(减号)uint = 无符号结果?

c++ - 移位运算符、位运算符和 sizeof 运算符产生的结果的值类别是什么?

C++ Boost::asio与Arduino的串行通信无法写入

c++ - 最短/最便宜的路径?这里如何使用动态规划?

c++ - FBX SDK 返回 4 个顶点,而预期是 3 个顶点