首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::align

Defined in header <memory>

void* align( std::size_t alignment, std::size_t size, void*& ptr, std::size_t& space );

(since C++11)

给定指针ptr大小缓冲器space,返回由指定的alignmentsize字节数和减少数space参数由用于对齐的字节数设置。返回第一个对齐地址。

该函数仅在可能满足给定对齐对齐对齐对齐的字节数的情况下修改指针。如果缓冲区太小,则函数将不执行任何操作并返回。nullptr...

如果实现%28支持的对齐不是基本的或扩展的对齐值,则行为是未定义的,直到C++17%29电源为2%28,因为C++17%29。

参数

alignment

-

the desired alignment

size

-

the size of the storage to be aligned

ptr

-

pointer to contiguous storage of at least space bytes

space

-

the size of the buffer in which to operate

返回值

调整值ptr,如果所提供的空间太小,则为空指针值。

演示使用std::对齐将不同类型的对象放置在内存中。

二次

代码语言:javascript
复制
#include <iostream>
#include <memory>
 
template <std::size_t N>
struct MyAllocator
{
    char data[N];
    void* p;
    std::size_t sz;
    MyAllocator() : p(data), sz(N) {}
    template <typename T>
    T* aligned_alloc(std::size_t a = alignof(T))
    {
        if (std::align(a, sizeof(T), p, sz))
        {
            T* result = reinterpret_cast<T*>(p);
            p = (char*)p + sizeof(T);
            sz -= sizeof(T);
            return result;
        }
        return nullptr;
    }
};
 
int main()
{
    MyAllocator<64> a;
 
    // allocate a char
    char* p1 = a.aligned_alloc<char>();
    if (p1)
        *p1 = 'a';
    std::cout << "allocated a char at " << (void*)p1 << '\n';
 
    // allocate an int
    int* p2 = a.aligned_alloc<int>();
    if (p2)
        *p2 = 1;
    std::cout << "allocated an int at " << (void*)p2 << '\n';
 
    // allocate an int, aligned at 32-byte boundary
    int* p3 = a.aligned_alloc<int>(32);
    if (p3)
        *p3 = 2;
    std::cout << "allocated an int at " << (void*)p3 << " (32 byte alignment)\n";
}

二次

可能的产出:

二次

代码语言:javascript
复制
allocated a char at 0x2ff21a08
allocated an int at 0x2ff21a0c
allocated an int at 0x2ff21a20 (32 byte alignment)

二次

另见

alignof operator

queries alignment requirements of a type (since C++11)

alignas specifier

specifies that the storage for the variable should be aligned by specific amount (C++11)

aligned_storage (C++11)

defines the type suitable for use as uninitialized storage for types of given size (class template)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券