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));
}
......
}