QVarLengthArray:棧數組+堆數組
- 初始給定大小,創建棧數組
- 當添加元素大於棧數組大小時,創建堆數組,並把棧數組內容copy到堆數組上
- 加快創建速度,適用於高頻率使用數組的代碼中
代碼解析:
template<class T, int Prealloc>
class QVarLengthArray
{
public:
inline explicit QVarLengthArray(int size = 0);
inline QVarLengthArray(const QVarLengthArray<T, Prealloc> &other);
inline ~QVarLengthArray();
private:
int a; // capacity
int s; // size
T *ptr; // data
union {
char array[Prealloc * sizeof(T)];
qint64 q_for_alignment_1;
double q_for_alignment_2;
};
};
template <class T, int Prealloc>
void QVarLengthArray<T, Prealloc>::realloc(int asize, int aalloc)
{
T *oldPtr = ptr;
int osize = s;
// 重新創建堆數組
if (aalloc != a) {
if (aalloc > Prealloc) {
T* newPtr = reinterpret_cast<T *>(malloc(aalloc * sizeof(T)));
ptr = newPtr;
a = aalloc;
} else {
ptr = reinterpret_cast<T *>(array);
a = Prealloc;
}
......
memcpy(ptr, oldPtr, copySize * sizeof(T));
}
......
}