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


  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值