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

以下三個函數定義爲頭文件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;
		}
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章