Creating a word aligned char vector

2019-08-02 03:38发布

问题:

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.