diff --git a/Core/List.cpp b/Core/List.cpp index a87bcf66..00d4640a 100644 --- a/Core/List.cpp +++ b/Core/List.cpp @@ -11,6 +11,11 @@ List::List(int size) //List::List(T* items, uint count) { Set(items, count); } +List::~List() +{ + if(_Arr && _Arr != Arr) delete _Arr; +} + int List::Count() const { return _Count; } // 添加单个元素 @@ -106,3 +111,28 @@ void*& List::operator[](int 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; +} diff --git a/Core/List.h b/Core/List.h index aca8d566..e6a852c7 100644 --- a/Core/List.h +++ b/Core/List.h @@ -7,6 +7,7 @@ class List public: explicit List(int count = 0); //List(void* items, uint count); + ~List(); int Count() const; diff --git a/Test/ListTest.cpp b/Test/ListTest.cpp index 76614fa3..8183bd55 100644 --- a/Test/ListTest.cpp +++ b/Test/ListTest.cpp @@ -133,6 +133,14 @@ void TestList() idx = list.FindIndex(buf2); 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(); //TestAssign2(); //TestCopy();