#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; }