NOPのための STL-Allocaterの設計と実装

9
NOP のののの STL-Allocater のののののの ogura 2013/05/25

description

NOPのための STL-Allocaterの設計と実装

Transcript of NOPのための STL-Allocaterの設計と実装

Page 1: NOPのための STL-Allocaterの設計と実装

NOP のためのSTL-Allocater の設計と実

装ogura

2013/05/25

Page 2: NOPのための STL-Allocaterの設計と実装

What's STL

Standard Template Library C++ で使えるわりと便利なライブラリ vector や string とか便利

• 標準ライブラリの参考になるサイトhttp://www.geocities.jp/ky_webid/cpp/library/

Page 4: NOPのための STL-Allocaterの設計と実装

自作アロケータの必要性 ゲーム制作におけるメモリ管理

• 常に 60FPS を維持したいnew/delete の処理時間は一定の方がいい→ 時間予見可能性メモリの確保の時間は OS 依存…というか一定でないことが多い

• 弾幕など大量のオブジェクトが生死するいちいち OS に依頼して管理するのは時間的にキツイ・・・自分でメモリプールなり用意した方がいいのでは?

Page 5: NOPのための STL-Allocaterの設計と実装

STL のアロケータ std::vector の定義

VisualC++ 2010 Express Edition の場合

template <class _Ty, class _Ax = allocator<_Ty> > class vector : public ...

アロケータを設定するところがある

std::allocator の定義

cplusplus.com さん : http://www.cplusplus.com/reference/memory/allocator/

Member functions(constructor)   Construct allocator object  (public member function )(destructor)     Allocator destructor        (public member function )address            Return address                (public member function )allocate            Allocate block of storage    (public member function )deallocate        Release block of storage    (public member function )max_size         Maximum size possible to allocate (public member function )construct         Construct an object            (public member function )destroy            Destroy an object               (public member function)

これだけメンバ関数があればいい

Page 6: NOPのための STL-Allocaterの設計と実装

自作アロケータを実装してみよう -1

仕様

ModernC++Design の SmallObjectAllocator っぽいやつメモリプール ( 配列 ) から固定長を確保 / 解放

free freeused used

new

object

new

object

配列 [オブジェクトの最大数

* オブジェクトサイズ ]

オブジェクトの最大数 =4オブジェクトのサイズ =2

Page 7: NOPのための STL-Allocaterの設計と実装

自作アロケータを実装してみよう -2

仕様

MemoryPool

MemoryIndex 2 2 3 4

• MemoryIndex は空き領域のリストになっている• 基本は [i]=i+1 で初期化• 空き領域の最初のインデックスは持っておく (mFreeIndex)

0 1 2 3

0mFreeIndex

new する時は、 mFreeIndex=MemoryIndex[mFreeIndex]; delete する時は、 mFreeIndex=(ptr/ オブジェクトのサイズ )-MemoryPool

Page 8: NOPのための STL-Allocaterの設計と実装

自作アロケータを実装してみよう -3

template<int SIZE> にするか template<class T> して sizeof(T) する placement new→ メモリプールから new する

●C++ 編(標準ライブラリ) 第28章 アロケータ (http://www.geocities.jp/ky_webid/cpp/library/028.html)

SmallObjectAllocator に対して SlabAllocator な拡張ができると Best

知っていると幸せになれること

Page 9: NOPのための STL-Allocaterの設計と実装

お・わ・り