【发布时间】:2017-06-17 14:55:42
【问题描述】:
我有一个非虚拟类模板A,如下所示,我执行以下操作
#include <iostream>
// my class template
template<typename T>
class A
{
public:
T x;
T y;
T z;
// bunch of other non-virtual member functions including constructors, etc
// and obviously no user-defined destructor
// ...
};
int main()
{
//now I do the following
A<double> a;
a.x = 1.0; // not important this
a.y = 2.0;
a.z = 3.0;
// now the concerned thing
double* ap = (double*)&a;
double* xp = &(a.x);
// can I correctly and meaningfully do the following?
double new_az = ap[2]; // guaranteed to be same as a.z (for any z) ? ** look here **
double new_z = xp[2]; // guaranteed to be same as a.z (for any z) ? ** look here **
std::cout<<new_az<<std::endl;
std::cout<<new_z<<std::endl;
return 0;
}
那么,如果我使用原始点指向对象A 或成员变量a.x,是否可以保证,我将正确获取其他变量?
【问题讨论】:
-
你为什么要这样做,而不是仅仅使用
std::array? -
@CodyGray 虽然我这里的演示课很简单。我的实际课程更复杂。而且我必须将其成员变量传递给库中的函数(这不是我的,并且出于某些明显的原因使用指针接口)。这就是为什么我立刻想到了这两个选项。
-
没有这样的保证。该标准规定
x、y和z将具有increasing addresses,但不排除在它们之间插入私有或受保护成员。 -
编译器也允许在成员之间添加填充以优化内存访问模式。例如,如果您创建一个
struct A { char x; int y },则很可能在x和y之间会有一些未使用的字节,这只是因为在对齐时访问int会更快。 -
@yeputons 如果情况只是 T 类型的 x、y、z 怎么办?在函数参数中将函数与此类类链接时会发生什么?
标签: c++ class data-structures memory-layout