变体类型存储和对齐问题 [英] Variant type storage and alignment issues

查看:91
本文介绍了变体类型存储和对齐问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经制作了一个变体类型来代替boost :: variant.我的工作是在可能的类型列表上存储当前类型的索引,并将数据存储在具有足够空间以存储最大类型的字节数组中.

I've made a variant type to use instead of boost::variant. Mine works storing an index of the current type on a list of the possible types, and storing data in a byte array with enough space to store the biggest type.

unsigned char data[my_types::max_size];
int type;

现在,当我向此变量类型写入值时会遇到麻烦.我使用以下内容:

Now, when I write a value to this variant type comes the trouble. I use the following:

template<typename T>
void set(T a) {
   int t = type_index(T);
   if (t != -1) {
      type = t;
      puts("writing atom data");
      *((T *) data) = a; //THIS PART CRASHES!!!!
      puts("did it!");
    } else {
      throw atom_bad_assignment;
    }
}

崩溃的那一行是将数据存储到内部缓冲区的那一行.如您所见,我只是将字节数组直接转换为所需类型的指针.尝试写一些值时,这给了我错误的地址信号和总线错误.

The line that crashes is the one that stores data to the internal buffer. As you can see, I just cast the byte array directly to a pointer of the desired type. This gives me bad address signals and bus errors when trying to write some values.

我在64位系统上使用GCC.如何设置字节数组的对齐方式,以确保该数组的地址是64位对齐的? (或针对我可能会将此项目移植到的任何体系结构进行适当调整).

I'm using GCC on a 64-bit system. How do I set the alignment for the byte array to make sure the address of the array is 64-bit aligned? (or properly aligned for any architecture I might port this project to).

谢谢大家,但是错误在其他地方.显然,英特尔并不真正在乎对齐.对齐的内容速度更快,但不是强制性的,程序可以通过这种方式很好地工作.我的问题是我在写东西之前没有清除数据缓冲区,这给某些类型的构造函数带来了麻烦.但是,我不会将问题标记为已回答,因此更多的人可以给我有关对齐的提示;)

Thank you all, but the mistake was somewhere else. Apparently, Intel doesn't really care about alignment. Aligned stuff is faster but not mandatory, and the program works fine this way. My problem was I didn't clear the data buffer before writing stuff and this caused trouble with the constructors of some types. I will not, however, mark the question as answered, so more people can give me tips on alignment ;)

推荐答案

请参见 http://gcc.gnu.org/onlinedocs/gcc-4.0.4/gcc/Variable-Attributes.html

unsigned char data[my_types::max_size] __attribute__ ((aligned));
int type;

这篇关于变体类型存储和对齐问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆