QVarLengthArray解析

QVarLengthArray:棧數組+堆數組

  1. 初始給定大小,創建棧數組
  2. 當添加元素大於棧數組大小時,創建堆數組,並把棧數組內容copy到堆數組上
  3. 加快創建速度,適用於高頻率使用數組的代碼中

代碼解析:

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章