【发布时间】:2015-09-04 10:21:45
【问题描述】:
我总是在 C 中填充我的结构以获得最佳性能(良好的内存对齐)。
// on a x86_64
struct A {
int64_t z;
int32_t x;
int16_t y;
// we don't care the uint8_t position, as they are 1 byte wide.
uint8_t s[8];
uint8_t t[4];
}
但如果我决定走 c++ 路线,为其他目的创建一个对象,我需要一个类:
class B {
B(){}
~B(){}
public:
int64_t a;
int8_t b;
private:
int32_t c;
//methods...
}
那么,c 就不再对齐了。
有没有办法避免这样做(多个标签):
class B {
B(){}
~B(){}
public:
int64_t a;
private:
int32_t c;
public:
int8_t b;
}
(在某些 CPU 上,对齐很重要)。 谢谢
【问题讨论】:
-
我怀疑这个类没有对齐
-
这不是关于类,而是关于它里面的变量。我找不到任何说它是自动对齐和正确组织的。我不想丢失太多字节。
-
我怀疑班级成员没有对齐
-
在您用尽所有其他优化之前,您甚至不应该考虑对您的代码执行此操作吗?首先编写可读性好的代码,然后找出需要修剪的地方。
标签: c++ class struct alignment