aligned_storage简单学习

简介: #include #include #include /* template< std::size_t Len, std::size_t Align = default-alignment >struct::type aligned_storage; 相当于一个内建的POD类...
#include <iostream>
#include <type_traits>
#include <string>

/*
template< std::size_t Len, std::size_t Align = default-alignment >struct::type aligned_storage;
相当于一个内建的POD类型他的大小是Size他的对齐方式是Align 
*/
template<class  T, std::size_t N>
class static_vector
{
    typename std::aligned_storage<sizeof(T), __alignof(T)>::type data[N];
    std::size_t m_size = 0;
public:

    //类似于vector的push_back,使用了变长模板参数
    //和placement new
    template<typename ...Args>
    void emplace_back(Args&&... args)
    {
        if (m_size >= N)
            throw std::bad_alloc{};
        new(data + m_size) T(std::forward<Args>(args)...);
        ++m_size;
    }
    const T & operator[](std::size_t pos) const
    {
        const T *  ret = reinterpret_cast<const T*>(data + pos);
        return *ret;
    }
    ~static_vector()
    {
        for (std::size_t pos = 0; pos < m_size; ++pos)
            reinterpret_cast<T*>(data + pos)->~T();
    }
};


int _tmain(int argc, _TCHAR* argv[])
{
    std::cout << __alignof(std::string) << std::endl;

    static_vector<std::string, 10> v1;
    v1.emplace_back(5, '*');
    v1.emplace_back(10, '*');

    std::cout << v1[0] << '\n' << v1[1] << '\n';
    return 0;
}

 

相关文章
|
11月前
|
存储 Web App开发 移动开发
📕Local Storage、Session Storage和Cache Storage之间的区别
你知道什么是Cache Storage、Local Storage和Session Storage吗?它们都是一些可以在你的浏览器里保存信息的介质,但是它们有什么不同呢?🤔
407 0
📕Local Storage、Session Storage和Cache Storage之间的区别
《Performance Characterization of In-Memory Data Analytics on a Scale-up Server》电子版地址
Performance Characterization of In-Memory Data Analytics on a Scale-up Server
60 0
《Performance Characterization of In-Memory Data Analytics on a Scale-up Server》电子版地址
|
存储 Web App开发 移动开发
storage
在HTML5出现之前,如果开发者需要在客户端存储少量的数据,只能通过cookie来实现,但是cookie存在几个不足点: 每个域名下cookie的大小限制在4KB。 cookie会包含在每个http请求中,这样会导致发送重复的数据。 cookie在网络传输过程中没有加密,存在安全隐患。 在HTML5新增了Web storage功能,Web Storage官方建议为每个网站是5MB,能存储比cookie更多的数据,并且具有比cookie更强大的功能。Web Storage现在已经得到了Firefox、Opera、Chrome、Safari各主流浏览器的支持。
284 0
storage
SAP WM初阶Interim Storage Type不好启用Storage Unit Management
SAP WM初阶Interim Storage Type不好启用Storage Unit Management
SAP WM初阶Interim Storage Type不好启用Storage Unit Management
|
JavaScript 前端开发
|
JavaScript 前端开发 内存技术
|
存储 数据库 文件存储