标签:动态数组 result 文件 为我 qtp 不同 引用计数 正是 开头
size_type _M_check_len(size_type __n, const char* __s) const { if (max_size() - size() < __n) __throw_length_error(__N(__s)); const size_type __len = size() + std::max(size(), __n); return (__len < size() || __len > max_size()) ?max_size() : __len; }
vector<int> ve(4, 8); cout << "size : " << ve.size() << " capacity : " << ve.capacity() << endl; for ( int i = 0; i < 14; ++i ) { ve.push_back(9); ve.push_back(0); cout << "size : " << ve.size() << " capacity : " << ve.capacity() << endl; }
inline void push_back(const T &t) { append(t); }
const bool isTooSmall = uint(d->size + 1) > d->alloc; if (!isDetached() || isTooSmall) { QArrayData::AllocationOptions opt(isTooSmall ?QArrayData::Grow : QArrayData::Default); reallocData(d->size, isTooSmall ? d->size + 1 : d->alloc, opt); }
因为内存分配可能是由写时复制策略调用,因此依据 isTooSmall 參数的不同。reallocData()的參数也不同。
static QTypedArrayData *allocate(size_t capacity, AllocationOptions options = Default) Q_REQUIRED_RESULT { Q_STATIC_ASSERT(sizeof(QTypedArrayData) == sizeof(QArrayData)); return static_cast<QTypedArrayData *>(QArrayData::allocate(sizeof(T), Q_ALIGNOF(AlignmentDummy), capacity, options)); }
class AlignmentDummy { QArrayData header; T data; };
QtPrivate::RefCount ref; int size; uint alloc : 31; uint capacityReserved : 1; qptrdiff offset; // in bytes from beginning of header
QArrayData *QArrayData::allocate(size_t objectSize, size_t alignment, size_t capacity, AllocationOptions options) { // 检測aligment是否为2的阶数倍 Q_ASSERT(alignment >= Q_ALIGNOF(QArrayData) && !(alignment & (alignment - 1))); ... // 获取 QArrayData 类为空时的大小 size_t headerSize = sizeof(QArrayData); // 申请额外的 alignment-Q_ALIGNOF(QArrayData)大小的 padding 字节数 // 这样就能将数据放在合适的位置上 if (!(options & RawData)) headerSize += (alignment - Q_ALIGNOF(QArrayData)); // 假设数组长度超出容量则申请新的内存 if (options & Grow) capacity = qAllocMore(int(objectSize * capacity), int(headerSize)) / int(objectSize); //一共须要申请的字节数 size_t allocSize = headerSize + objectSize * capacity; QArrayData *header = static_cast<QArrayData *>(::malloc(allocSize)); if (header) { ... } return header; }
int qAllocMore(int alloc, int extra) { Q_ASSERT(alloc >= 0 && extra >= 0); Q_ASSERT_X(alloc < (1 << 30) - extra, "qAllocMore", "Requested size is too large!"); unsigned nalloc = alloc + extra; // Round up to next power of 2 // Assuming container is growing, always overshoot //--nalloc; nalloc |= nalloc >> 1; nalloc |= nalloc >> 2; nalloc |= nalloc >> 4; nalloc |= nalloc >> 8; nalloc |= nalloc >> 16; ++nalloc; Q_ASSERT(nalloc > unsigned(alloc + extra)); return nalloc - extra; }
alloc是我们存放实际数据区域的大小,nalloc即为我们总共须要的新内存容量。
QVector<int> ve(2, 8); qDebug() << "size : " << ve.size() << " capacity : " << ve.capacity(); for ( int i = 0; i < 20; ++i ) { ve.append(9); qDebug() << "size : " << ve.size() << " capacity : " << ve.capacity(); }
标签:动态数组 result 文件 为我 qtp 不同 引用计数 正是 开头
原文地址:http://www.cnblogs.com/brucemengbm/p/6809381.html