创建一个单词对齐的char向量 [英] Creating a word aligned char vector

查看:97
本文介绍了创建一个单词对齐的char向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个原始缓冲区数据类,它必须返回一个指向 char 的指针,该指针必须保证字对齐。

I need to create a raw buffer data class, it has to return a pointer to char that is guaranteed to be word aligned.

我正在考虑使用 std :: vector<<< something>>。 vec

我知道 std :: vector 将使用 operator new 分配内存,该内存可以保证返回最大对齐的内存,但我不想依赖于此。

I know that most (if not all) implementations of std::vector will use operator new to allocate memory which is guaranteed to return maximally aligned memory but I don't want to rely on that.

我也不想创建自己的对齐分配器。

I don't want to create my own aligned allocator either. Seems like overkill.

这就是我想出的:(假装 uintptr_t 肯定有单词大小)

This is what I came up with: (lets pretend that uintptr_t is guaranteed to have word size)

typedef uintptr_t WORD_TYPE;

std::vector<WORD_TYPE> vec;

然后我用它来访问数据:

And then I use this to access the data:

reinterpret_cast<char*>(vec.data());

我看不到这种方法有什么问题。

I can't see find any problems with this approach. Is it correct or is there a better way considering the requirements listed?

推荐答案

SO帖子指出 new 运算符可确保对齐任何对象类型。只需使用 std :: vector< char> 即可满足您的需求;就像您说的那样, std :: vector 在我见过的每个实现中都使用 new ,这意味着至少单词对齐

The accepted answer in this SO post states that the new operator does guarantee alignment for any object type. Simply using std::vector<char> should suit your needs; like you say, std::vector uses new in every implementation I've seen and that implies at least word alignment.

这篇关于创建一个单词对齐的char向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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