打包包含字符串的结构
Packing a struct that contains a string
我刚刚了解了填充,我正在尝试对其进行一些测试,
我试图打包这个结构:
struct B {
int a,b,c;
string s;
char x;
string t;
char y;
string u;
}__attribute__((packed)) ;
但是我收到这个警告:
warning: ignoring packed attribute because of unpacked non-POD field 'std::string B::u'
string u;
这是否意味着包含 strings
的结构无法打包?还有其他方法吗?如果是这样会影响性能吗?
一个好的经验法则是将您的成员从大到小排序。这样您的数据就会对齐并且(通常)没有间隙。例如。在 VS2013 上,对于 x64 目标,以下布局需要 112 个字节而不是 128 个字节:
struct B {
string s,t,u;
int a,b,c;
char x,y;
};
然而,对于 x86 目标,这只会为您节省 4 个字节。这是否以及如何影响您的表现取决于许多其他因素,只能通过测量来确定。
我刚刚了解了填充,我正在尝试对其进行一些测试, 我试图打包这个结构:
struct B {
int a,b,c;
string s;
char x;
string t;
char y;
string u;
}__attribute__((packed)) ;
但是我收到这个警告:
warning: ignoring packed attribute because of unpacked non-POD field 'std::string B::u'
string u;
这是否意味着包含 strings
的结构无法打包?还有其他方法吗?如果是这样会影响性能吗?
一个好的经验法则是将您的成员从大到小排序。这样您的数据就会对齐并且(通常)没有间隙。例如。在 VS2013 上,对于 x64 目标,以下布局需要 112 个字节而不是 128 个字节:
struct B {
string s,t,u;
int a,b,c;
char x,y;
};
然而,对于 x86 目标,这只会为您节省 4 个字节。这是否以及如何影响您的表现取决于许多其他因素,只能通过测量来确定。