1

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?

imreal
  • 10,178
  • 2
  • 32
  • 48

1 Answers1

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.

jotik
  • 17,044
  • 13
  • 58
  • 123
joshwilsonvu
  • 2,569
  • 9
  • 20
  • I do need it to be dynamically sized. And I cant rely on `vector` being implemented with `operator new` even if it is in practice. – imreal Aug 03 '17 at 17:41
  • 1
    Then if you don't need to resize the buffer at runtime, I would suggest creating a class that uses `new[]` to allocate the desired length unsigned char[] array in the constructor, `delete[]` in the destructor, and a getData() method. If you don't trust new's alignment, you could create the class with two pointers; one to allocate and deallocate the memory, allocating a word minus one byte of extra memory, and the other to start at the address of the first and iterate forward until the address it points to is correctly aligned. The second pointer would then be used for an aligned getData(). – joshwilsonvu Aug 03 '17 at 17:50
  • I might have to do that. – imreal Aug 03 '17 at 17:57
  • 1
    @imreal if you go with 2 pointer approach - you do not need to allocate by yourself - use vector as storage, and pointer to aligned start inside the vector – Artemy Vysotsky Aug 22 '17 at 18:16