標題において、実装コードに疑問があります。
以下のコードのconstructメンバ関数で、placement newに渡すポインタをボイドポインターにキャストして渡しています。
なぜ、キャストしているのでしょうか。
また、new((void*)p) T(value)で、コピーコンストラクター?を呼んで、オブジェクトを構築していますが、なぜコピーコンストラクタを呼び出すのでしょうか。
デフォルトコンストラクターでは、不都合があるのでしょうか。
引用サイト: C++編(標準ライブラリ) 第28章 アロケータ
C++
1template <class T> 2class allocator 3{ 4public: 5 // 型定義 6 typedef size_t size_type; 7 typedef ptrdiff_t difference_type; 8 typedef T* pointer; 9 typedef const T* const_pointer; 10 typedef T& reference; 11 typedef const T& const_reference; 12 typedef T value_type; 13 14 // アロケータをU型にバインドする 15 template <class U> 16 struct rebind 17 { 18 typedef allocator<U> other; 19 }; 20 21 // コンストラクタ 22 allocator() throw(){} 23 allocator(const allocater&) throw(){} 24 template <class U> allocator(const allocator<U>&) throw(){} 25 // デストラクタ 26 ~allocator() throw(){} 27 28 // メモリを割り当てる 29 pointer allocate(size_type num, allocator<void>::const_pointer hint = 0) 30 { 31 return (pointer)( ::operator new( num * sizeof(T) ) ); 32 } 33 // 割当て済みの領域を初期化する 34 void construct(pointer p, const T& value) 35 { 36 new( (void*)p ) T(value); 37 } 38 39 // メモリを解放する 40 void deallocate(pointer p, size_type num) 41 { 42 ::operator delete( (void*)p ); 43 } 44 // 初期化済みの領域を削除する 45 void destroy(pointer p) 46 { 47 p->~T(); 48 } 49 50 // アドレスを返す 51 pointer address(reference value) const { return &value; } 52 const_pointer address(const_reference value) const { return &value; } 53 54 // 割当てることができる最大の要素数を返す 55 size_type max_size() const throw() 56 { 57 return numeric_limits<size_t>::max() / sizeof(T); 58 } 59};
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。