C++ Utilities四(Uninitialized memory的使用)

来源:互联网 发布:淘宝店铺售后服务 编辑:程序博客网 时间:2024/06/04 19:27
以下三个函数定义为头文件memory中,下面是其可能的实际代码。代码来源于《The C++ Standard Library》namespace std{template<class ForwIter,class T>void uninitialized_fill(ForwIter beg,ForwIter end, const T& value){typedef typename iterator_traits<ForwIter>::value_type VT;ForwIter save(beg);try{for(;beg != end; ++beg){new (static_cast<void *>(& *beg)) VT(value);}}catch(...){for(; save != beg; ++save){save->~VT();}throw;}}template<class ForwIter,class Size,class T>void uninitialized_fill_n(ForwIter beg,Size num, const T& value){typedef typename iterator_traits<ForwIter>::value_type VT;ForwIter save(beg);try{for(;num--; ++beg){new (static_cast<void *>(& *beg)) VT(value);}}catch(...){for(; save != beg; ++save){save->~VT();}throw;}}template<class InputIter,class ForwIter>void uninitialized_copy(InputIter beg,InputIter end, ForwIter dest){typedef typename iterator_traits<ForwIter>::value_type VT;ForwIter save(dest);try{for(;beg != end; ++beg,++dest){new (static_cast<void *>(& *dest)) VT(*beg);}}catch(...){for(; save != dest; ++save){save->~VT();}throw;}}}