java数组模拟及越界检查

手边有不少java代码,中间使用了大量的数组,然后程序中使用大量的.length的方法来获得数组的元素个数,而这一切,在C++却没有,给代码移植带来不少麻烦,于是,就写了下面的模板:

#ifndef _H_ARRAY
#define _H_ARRAY
#include "AEEStdlib.H"
#include "define.h"
#include "MemoryAlloc.h"

template < typename T, int alength = 0 >
class ARRAY 
	{
	public:
		typedef ARRAY< T, alength  > ARRAY_TYPE;
		T* buf;	
		int length;
		
		ARRAY() : buf( NULL ), length( 0 )
			{
			if( alength != 0 )
				{
				buf = new (STACK) T[alength];
				if( buf == NULL )
					return;
				length = alength;
				MEMSET( buf, 0, sizeof(T) * length );
				}

			}
		
		~ARRAY()
			{
			delete[] buf;
			}
		
		ARRAY( T* abuf, int alength ): buf( NULL )
			{
			if( alength == 0 )
				{
				buf = NULL;
				length = 0;
				return;
				}
			buf = abuf;
			length = alength;		
			}
		
		inline int Length()
			{ 
			return length;
			}
		
		ARRAY( const ARRAY_TYPE& aright )
			{
			if( aright.length == 0 )
				{
				//delete buf;
				buf = NULL;
				length = aright.length;
				return;
				}
		
			buf = new (STACK) T[aright.length];
			if( buf == NULL )
				{//
				length = 0;
				return;
				}
			for( int i = 0; i < aright.length; i++ )
				buf[i] = aright[i];
			length = aright.length;
			}
		
		inline void SetData( T* adata, int alength )
			{
			if( buf )
				delete[] buf;
			buf = adata;
			length = alength;		
			}
		
		void clear()
			{
			delete[] buf;
			buf = NULL;
			length = 0;
			}
		
		inline operator T*() const
			{
			return buf;
			}
	
		ARRAY_TYPE&  operator=( const ARRAY_TYPE& aright )
			{
			if( this->buf == aright.buf )
				return *this;
			if( buf )
				delete[] buf;
			buf = NULL;
			length = 0;
			if( aright.length == NULL )
				return *this;
			buf = new (STACK) T[aright.length];
			if( buf == NULL )
				{
				return *this;
				}
			for( int i = 0; i < aright.length; i++ )
				buf[i] = aright[i];
			length = aright.length;
			return *this;
			}
	};

#endif

当使用数组形式时的时候,会转换成指针的调用,这样可以加快速度。如果代码写的统一的话,可以添加一个函数:

       inline T& operator T[](int a) const
       {
       if (a >=length) {
       DBGPRINTF("error:%d", a);
       }
       return buf[i];
       }
       

这样可以进行数组的越界检查。我曾经用上面的方法检查出一个很隐藏的数组越界。

发布者

rix

如果连自己都不爱自己,哪还有谁来爱你