How to align pointer

前端 未结 6 2367
说谎
说谎 2020-12-01 04:29

How do I align a pointer to a 16 byte boundary?

I found this code, not sure if its correct

char* p= malloc(1024);

if ((((unsigned long) p) % 16) !=          


        
6条回答
  •  误落风尘
    2020-12-01 05:34

    C++0x proposes std::align, which does just that.

    // get some memory
    T* const p = ...;
    std::size_t const size = ...;
    
    void* start = p;
    std::size_t space = size;
    void* aligned = std::align(16, 1024, p, space);
    if(aligned == nullptr) {
        // failed to align
    } else {
        // here, p is aligned to 16 and points to at least 1024 bytes of memory
        // also p == aligned
        // size - space is the amount of bytes used for alignment
    }
    

    which seems very low-level. I think

    // also available in Boost flavour
    using storage = std::aligned_storage_t<1024, 16>;
    auto p = new storage;
    

    also works. You can easily run afoul of aliasing rules though if you're not careful. If you had a precise scenario in mind (fit N objects of type T at a 16 byte boundary?) I think I could recommend something nicer.

提交回复
热议问题