zoukankan      html  css  js  c++  java
  • aligned_storage简单学习

    #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] << '
    ' << v1[1] << '
    ';
        return 0;
    }
  • 相关阅读:
    检测是否安装了新包
    redux和mobx的比较
    ssh登录远程服务器
    法律
    如何解决二方包彼此依赖?
    创业
    【转】裸辞4个月,面试30家公司。
    添加群机器人
    RESTful状态码说明
    MongoDB简单介绍以及基本命令
  • 原文地址:https://www.cnblogs.com/zhangdongsheng/p/7028055.html
Copyright © 2011-2022 走看看