CrossFramework Library
|
00001 00006 #if defined(XBASE_INCLUDED_RUNTIMEARRAY_HPP) 00007 #else 00008 #define XBASE_INCLUDED_RUNTIMEARRAY_HPP 00009 00010 //------------------------------------------------------------ 00011 #include <XBase/Compiler.hpp> 00012 #include <XBase/IAllocator.hpp> 00013 #include <XBase/NonCopyable.hpp> 00014 #include <XBase/RuntimeAssert.hpp> 00015 00016 //------------------------------------------------------------ 00017 namespace XBase { 00019 00020 00021 template< typename T > 00022 class RuntimeArray : public ::XBase::NonCopyable 00023 { 00024 public: 00026 00027 typedef T ValueType; 00029 00031 00032 00040 RuntimeArray( uint aCount , IAllocator& aAllocator = IAllocator::Default() ) 00041 : mAllocator( aAllocator ) 00042 , mCount( aCount ) 00043 , mPtr( 0 ) 00044 { 00045 if ( 0 < mCount ) 00046 { 00047 mPtr = reinterpret_cast< ValueType* >( mAllocator.alloc( sizeof( ValueType ) * mCount ) ); 00048 00049 for ( uint i = 0; i < aCount; ++i ) 00050 { 00051 #if defined(XBASE_COMPILER_MSVC) 00052 #pragma warning(push) 00053 #pragma warning(disable: 4345) 00054 #endif 00055 new ( &at(i) ) ValueType(); // 初期値で初期化 00056 #if defined(XBASE_COMPILER_MSVC) 00057 #pragma warning(pop) 00058 #endif 00059 } 00060 } 00061 } 00062 00064 ~RuntimeArray() 00065 { 00066 if ( mPtr != 0 ) 00067 { 00068 // 逆順でデストラクタを呼び出す 00069 for ( uint i = mCount; 0 < i; --i ) 00070 { 00071 at( i -1 ).~ValueType(); 00072 } 00073 00074 ValueType* ptr = mPtr; 00075 mPtr = 0; 00076 mAllocator.free( reinterpret_cast< ptr_t >( ptr ) ); 00077 } 00078 } 00079 00081 00083 00084 00085 uint count()const 00086 { 00087 return mCount; 00088 } 00089 00091 ValueType& at( const uint aIndex ) 00092 { 00093 if ( mCount <= aIndex ) 00094 { 00095 XBASE_RANGE_ASSERT_MAX( aIndex , mCount ); 00096 return mPtr[ 0 ]; // fail safe code 00097 } 00098 return mPtr[ aIndex ]; 00099 } 00100 00102 const ValueType& at( const uint aIndex )const 00103 { 00104 if ( mCount <= aIndex ) 00105 { 00106 XBASE_RANGE_ASSERT_MAX( aIndex , mCount ); 00107 return mPtr[ 0 ]; // fail safe code 00108 } 00109 return mPtr[ aIndex ]; 00110 } 00111 00113 00115 00116 ValueType& operator[]( const uint aIndex ) { return at( aIndex ); } 00117 const ValueType& operator[]( const uint aIndex )const { return at( aIndex ); } 00118 00119 00120 private: 00121 IAllocator& mAllocator; 00122 const uint mCount; 00123 ValueType* mPtr; 00124 }; 00126 } 00127 //------------------------------------------------------------ 00128 #endif 00129 // EOF