c++ - Align a pointer -


i want align pointer p p = (modulo b). of time, = 0 , b = 32 or 64 simd alignement, might want = 64 , b = 128 when want fine tune algorithm cache associativity.

  • std::align not accept power of 2 alignement. fixed in c++17, useless right now
  • __mm_malloc/__free not portable want

my best solution far cast pointer std::uintptr_t , use modulo operations on integers move pointer. unfortunately, not portable casting pointer std::uintptr_t not "allowed". works on platforms have tried far.

on kind of platform such code break?

might this:

inline size_t alignhi(size_t size, size_t align) {     return (size + align - 1) & ~(align - 1); }  inline void * allocate(size_t size, size_t align) { #if defined(_msc_ver)      return _aligned_malloc(size, align); #elif defined(__gnuc__)     align = alignhi(align, sizeof(void*));     size = alignhi(size, align);     void * ptr;     int result = ::posix_memalign(&ptr, align, size);     return result ? null : ptr; #else     return malloc(size); #endif }  inline void free(void * p) { #if defined(_msc_ver)      _aligned_free(p); #else     free(p); #endif } 

Comments