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

std::aligned_storage

Defined in header <type_traits>

?

?

template< std::size_t Len, std::size_t Align = /*default-alignment*/ > struct aligned_storage;

?

(since C++11)

提供成员类型胡枝子f。type,这是PODType适合用作任何大小最多为零的对象的未初始化存储。Len谁的对齐要求是Align...

的默认值Align对于任何大小最多都是的对象,最严格的%28是最大的%29对齐要求吗?Len如果未使用默认值,Align必须是alignof(T)为某种类型T,或者行为是未定义的。

如果Len == 0...

成员类型

Name

Definition

type

the POD type of at least size Len with alignment requirement Align

帮助者类型

template< std::size_t Len, std::size_t Align = /*default-alignment*/ > using aligned_storage_t = typename aligned_storage<Len, Align>::type;

?

(since C++14)

注记

定义的类型。std::aligned_storage<>::type可用于创建未初始化的内存块,以容纳给定类型的对象,可选地比它们的自然对齐要求更严格,例如在缓存或页边界上。

与任何其他未初始化的存储一样,对象是使用安置新并通过显式析构函数调用销毁。

可能的实施

除默认参数外,对齐[医]存储可以用对齐表示:

模板<std::size[医]T Len,STD::大小[医]T对齐/%2A未实现默认对齐%2A/>结构对齐[医]存储{tydurif struct{对齐%28Align%29无符号字符数据伦;}型;};

*。

一个原始的静态向量类,演示对齐存储中对象的创建、访问和销毁。

二次

代码语言:javascript
复制
#include <iostream>
#include <type_traits>
#include <string>
 
template<class T, std::size_t N>
class static_vector
{
    // properly aligned uninitialized storage for N T's
    typename std::aligned_storage<sizeof(T), alignof(T)>::type data[N];
    std::size_t m_size = 0;
 
public:
    // Create an object in aligned storage
    template<typename ...Args> void emplace_back(Args&&... args) 
    {
        if( m_size >= N ) // possible error handling
            throw std::bad_alloc{};
        new(data+m_size) T(std::forward<Args>(args)...);
        ++m_size;
    }
 
    // Access an object in aligned storage
    const T& operator[](std::size_t pos) const 
    {
        return *reinterpret_cast<const T*>(data+pos);
    }
 
    // Delete objects from aligned storage
    ~static_vector() 
    {
        for(std::size_t pos = 0; pos < m_size; ++pos) {
            reinterpret_cast<T*>(data+pos)->~T();
        }
    }
};
 
int main()
{
    static_vector<std::string, 10> v1;
    v1.emplace_back(5, '*');
    v1.emplace_back(10, '*');
    std::cout << v1[0] << '\n' << v1[1] << '\n';
}

二次

产出:

二次

代码语言:javascript
复制
*****
**********

二次

另见

alignas specifier

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

alignment_of (C++11)

obtains the type's alignment requirements (class template)

aligned_union (C++11)

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

max_align_t (C++11)

POD type with alignment requirement as great as any other scalar type (typedef)

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

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

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com