未初期化ストレージuninitialized_x
また、allocator空間分配器のほか、には初期化容器標準ライブラリ関数がある.
それぞれ:
template inline _ForwardIterator uninitialized_copy(_InputIterator __first, _InputIterator __last,_ForwardIterator __result)
template inline void uninitialized_fill(_ForwardIterator __first, _ForwardIterator __last,const _Tp& __x)
template inline void uninitialized_fill_n(_ForwardIterator __first, _Size __n, const _Tp& __x)
それぞれ:
template
template
template
/*
* File: main.cpp
* Author: Vicky.H
* Email: [email protected]
*/
#include <iostream>
#include <memory>
#include <cstring>
struct st_A {
char name[21];
short age;
};
namespace cn_vicky_uninitialized {
/**
* stl
* @param first
* @param n
* @param val
*/
template <class For, class Size, class T>
inline void uninitialized_fill_n_stl(For first, Size n, const T& val) {
// typedef typename std::iterator_traits<For>::value_type VT;
// while (n--) std::_Construct(std::__addressof(*first++), static_cast<VT>(val));
while (n--) std::_Construct(std::__addressof(*first++), val);
}
/**
*
* @param first
* @param n
* @param val
*/
template <class For, class Size, class T>
inline void uninitialized_fill_n(For first, Size n, const T& val) {
typedef typename std::iterator_traits<For>::value_type VT;
while (n--) new (static_cast<void*> (&*first++)) VT(val); /** stl construct , new */
}
}
/*
*
*/
int main(void) {
st_A st_A_arr[10];
std::cout << st_A_arr[0].name << std::endl;
std::cout << st_A_arr[0].age << std::endl;
std::cout << st_A_arr[9].name << std::endl;
std::cout << st_A_arr[9].age << std::endl;
std::cout << "---------------------------" << std::endl;
// stl
st_A a;
strcpy(a.name, "Vicky");
a.age = 25;
std::uninitialized_fill_n(st_A_arr, 10, a);
std::cout << st_A_arr[0].name << std::endl;
std::cout << st_A_arr[0].age << std::endl;
std::cout << st_A_arr[9].name << std::endl;
std::cout << st_A_arr[9].age << std::endl;
std::cout << "---------------------------" << std::endl;
strcpy(a.name, "Lily");
a.age = 24;
cn_vicky_uninitialized::uninitialized_fill_n_stl(st_A_arr, 10, a);
std::cout << st_A_arr[0].name << std::endl;
std::cout << st_A_arr[0].age << std::endl;
std::cout << st_A_arr[9].name << std::endl;
std::cout << st_A_arr[9].age << std::endl;
std::cout << "---------------------------" << std::endl;
//
strcpy(a.name,"Jack");
a.age = 18;
cn_vicky_uninitialized::uninitialized_fill_n(st_A_arr, 10, a);
std::cout << st_A_arr[0].name << std::endl;
std::cout << st_A_arr[0].age << std::endl;
std::cout << st_A_arr[9].name << std::endl;
std::cout << st_A_arr[9].age << std::endl;
return 0;
}