热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

aligned_storage简单学习

#include<iostream>#include<type_traits>#include<string>*template<s
#include 
#include 
#include <string>

/*
templatestruct::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
    void emplace_back(Args&&... args)
    {
        if (m_size >= N)
            throw std::bad_alloc{};
        new(data + m_size) T(std::forward(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 pos)
            reinterpret_cast(data + pos)->~T();
    }
};


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

    static_vectorstring, 10> v1;
    v1.emplace_back(5, '*');
    v1.emplace_back(10, '*');

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

 


推荐阅读
author-avatar
手机用户2502939543
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有