增加自动扩容和自动释放
This commit is contained in:
parent
df308cbd5a
commit
b66a303d05
|
@ -11,6 +11,11 @@ List::List(int size)
|
||||||
|
|
||||||
//List::List(T* items, uint count) { Set(items, count); }
|
//List::List(T* items, uint count) { Set(items, count); }
|
||||||
|
|
||||||
|
List::~List()
|
||||||
|
{
|
||||||
|
if(_Arr && _Arr != Arr) delete _Arr;
|
||||||
|
}
|
||||||
|
|
||||||
int List::Count() const { return _Count; }
|
int List::Count() const { return _Count; }
|
||||||
|
|
||||||
// 添加单个元素
|
// 添加单个元素
|
||||||
|
@ -106,3 +111,28 @@ void*& List::operator[](int i)
|
||||||
|
|
||||||
return _Arr[i];
|
return _Arr[i];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool List::CheckCapacity(int count)
|
||||||
|
{
|
||||||
|
// 是否超出容量
|
||||||
|
if(_Arr && count <= _Capacity) return true;
|
||||||
|
|
||||||
|
// 自动计算合适的容量
|
||||||
|
int sz = 0x40 >> 2;
|
||||||
|
while(sz < count) sz <<= 1;
|
||||||
|
|
||||||
|
void* p = new byte[sz << 2];
|
||||||
|
if(!p) return false;
|
||||||
|
|
||||||
|
// 需要备份数据
|
||||||
|
if(_Count > 0 && _Arr)
|
||||||
|
// 为了安全,按照字节拷贝
|
||||||
|
Buffer(p, sz).Copy(0, _Arr, _Count << 2);
|
||||||
|
|
||||||
|
if(_Arr && _Arr != p) delete _Arr;
|
||||||
|
|
||||||
|
_Arr = (void**)p;
|
||||||
|
_Capacity = sz;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
|
@ -7,6 +7,7 @@ class List
|
||||||
public:
|
public:
|
||||||
explicit List(int count = 0);
|
explicit List(int count = 0);
|
||||||
//List(void* items, uint count);
|
//List(void* items, uint count);
|
||||||
|
~List();
|
||||||
|
|
||||||
int Count() const;
|
int Count() const;
|
||||||
|
|
||||||
|
|
|
@ -133,6 +133,14 @@ void TestList()
|
||||||
idx = list.FindIndex(buf2);
|
idx = list.FindIndex(buf2);
|
||||||
assert(idx == -1, "int FindIndex(const void* item)");
|
assert(idx == -1, "int FindIndex(const void* item)");
|
||||||
|
|
||||||
|
debug_printf("下面添加多项内容,将会引发List重新分配并拷贝内存\r\n需要注意new/delete\r\n");
|
||||||
|
for(int i=0; i<16; i++)
|
||||||
|
{
|
||||||
|
list.Add(buf1);
|
||||||
|
}
|
||||||
|
assert(list.Count() == 3 + 16, "Count()");
|
||||||
|
assert(list[0] == buf1 && list[1] == buf3 && list[2] == buf3, "bool CheckCapacity(int count)");
|
||||||
|
|
||||||
//TestAssign();
|
//TestAssign();
|
||||||
//TestAssign2();
|
//TestAssign2();
|
||||||
//TestCopy();
|
//TestCopy();
|
||||||
|
|
Loading…
Reference in New Issue