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

std::aligned_alloc

Defined in header <cstdlib>

?

?

void* aligned_alloc( std::size_t alignment, std::size_t size );

?

(since C++17)

分配size未初始化存储的字节,其对齐方式由alignment...size参数必须是alignment...

The following functions are required to be thread-safe: The library versions of operator new and operator delete User replacement versions of global operator new and operator delete std::calloc, std::malloc, std::realloc, std::aligned_alloc (since C++17) Calls to these functions that allocate or deallocate a particular unit of storage occur in a single total order, and each such deallocation call happens-before the next allocation (if any) in this order.

(since C++11)

  • 的库版本operator newoperator delete
  • 全局用户替换版本operator newoperator delete
  • std::calloc,,,std::malloc,,,std::realloc,,,std::aligned_alloc%28自C++17%29

对分配或释放特定存储单元的这些函数的调用是以单个总顺序进行的,并且每个这样的释放调用都会发生。发生-之前下一次按此顺序分配%28(如果有%29)。

%28自C++11%29

参数

alignment

-

specifies the alignment. Must be a valid alignment supported by the implementation.

size

-

number of bytes to allocate. An integral multiple of alignment

返回值

成功后,返回指向新分配内存开始的指针。返回的指针必须用free()realloc()...

失败时,返回一个空指针。

注记

擦肩而过size的整数倍数。alignment或者是alignment它不有效或不受实现支持,导致函数失败并返回空指针%28C11,如已发布的那样,指定了未定义的行为--在这种情况下,这是由DR 460%29纠正的。

作为“受实现支持的”要求的一个例子,POSIX函数POSIX[医]备忘录接受任何alignment的乘幂sizeof(void*)的基于POSIX的实现aligned_alloc继承此要求。

正规化std::malloc对齐适合于任何对象类型%28的内存,在实践中,这意味着它对齐到alignof(std::max_align_t)29%。此函数对于超对齐分配非常有用,例如对SSE、缓存行或VM页边界的分配。

二次

代码语言:javascript
复制
#include <cstdio>
#include <cstdlib>
 
int main()
{
    int* p1 = std::malloc(10*sizeof *p1);
    std::printf("default-aligned addr:   %p\n", (void*)p1);
    std::free(p1);
 
    int* p2 = std::aligned_alloc(1024, 1024*sizeof *p2);
    std::printf("1024-byte aligned addr: %p\n", (void*)p2);
    std::free(p2);
}

二次

可能的产出:

二次

代码语言:javascript
复制
default-aligned addr:   0x2221c20
1024-byte aligned addr: 0x2222000

二次

另见

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。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com