// Wrapper.cppstructWrapper::Wrapped{};Wrapper::Wrapper(){static_assert(sizeof(Wrapped)<=sizeof(this->storage),"Object can't fit into local storage");// 采用placement new构造Wrappedthis->handle=new(&this->storage)Wrapped();}Wrapper::~Wrapper(){// 显示的析构handle->~Wrapped();}
#include<iostream>// objects of type S can be allocated at any address// because both S.a and S.b can be allocated at any addressstructS{chara;// size: 1, alignment: 1charb;// size: 1, alignment: 1};// size: 2, alignment: 1// objects of type X must be allocated at 4-byte boundaries// because X.n must be allocated at 4-byte boundaries// because int's alignment requirement is (usually) 4structX{intn;// size: 4, alignment: 4charc;// size: 1, alignment: 1// three bytes of padding bits};// size: 8, alignment: 4 intmain(){std::cout<<"alignof(S) = "<<alignof(S)<<'\n'<<"sizeof(S) = "<<sizeof(S)<<'\n'<<"alignof(X) = "<<alignof(X)<<'\n'<<"sizeof(X) = "<<sizeof(X)<<'\n';}// alignof(S) = 1// sizeof(S) = 2// alignof(X) = 4// sizeof(X) = 8
#include<cstddef>#include<iostream>#include<new>#include<string>#include<type_traits>template<classT,std::size_tN>classstatic_vector{// Properly aligned uninitialized storage for N T'sstd::aligned_storage_t<sizeof(T),alignof(T)>data[N];std::size_tm_size=0;public:// Create an object in aligned storagetemplate<typename...Args>voidemplace_back(Args&&...args){if(m_size>=N)// Possible error handlingthrowstd::bad_alloc{};// Construct value in memory of aligned storage using inplace operator new::new(&data[m_size])T(std::forward<Args>(args)...);++m_size;}// Access an object in aligned storageconstT&operator[](std::size_tpos)const{// Note: std::launder is needed after the change of object model in P0137R1return*std::launder(reinterpret_cast<constT*>(&data[pos]));}// Destroy objects from aligned storage~static_vector(){for(std::size_tpos=0;pos<m_size;++pos)// Note: std::launder is needed after the change of object model in P0137R1std::destroy_at(std::launder(reinterpret_cast<T*>(&data[pos])));}};intmain(){static_vector<std::string,10>v1;v1.emplace_back(5,'*');v1.emplace_back(10,'*');std::cout<<v1[0]<<'\n'<<v1[1]<<'\n';}// output// *****// **********