Creating a word aligned char vector

戏子无情 提交于 2019-12-24 11:44:51

问题


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

I was thinking about using a std::vector<<something>> vec.

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.

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?


回答1:


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.



来源:https://stackoverflow.com/questions/45490761/creating-a-word-aligned-char-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!