reallocate() 和 allocate() 的区别

📌 reallocate()allocate() 的区别

在 C++ 的 std::vector 及其底层内存管理中,allocate()reallocate() 是两个核心的内存管理函数。它们的作用不同:

函数 作用 影响 size() 吗? 影响 capacity() 吗?
allocate(n) 分配 n 个元素的内存(不初始化) ❌ 否 ✅ 是
reallocate(n) 重新分配内存,拷贝旧数据,释放旧内存 ❌ 否 ✅ 是(通常 2 倍扩容)

📌 1. allocate(n): 仅分配内存

🔹 作用 :在 vector 需要更多空间时,allocate(n) 分配 n 个元素的 未初始化内存 ,但不会拷贝旧数据,也不会释放旧内存

📌 示例

cpp 复制代码
#include <iostream>
#include <memory>  // 使用 std::allocator

int main() {
    std::allocator<int> alloc;
    
    int* arr = alloc.allocate(10); // 分配 10 个 int 空间(未初始化)
    
    for (int i = 0; i < 10; i++) {
        alloc.construct(arr + i, i * 10); // 手动构造对象
    }

    std::cout << "Allocated array: ";
    for (int i = 0; i < 10; i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    for (int i = 0; i < 10; i++) {
        alloc.destroy(arr + i); // 手动析构
    }
    alloc.deallocate(arr, 10); // 释放内存

    return 0;
}

📌 输出

复制代码
Allocated array: 0 10 20 30 40 50 60 70 80 90

allocate(n) 只分配内存,不初始化元素!

construct() 负责初始化对象,destroy() 负责析构,deallocate() 负责释放内存


📌 2. reallocate(n): 重新分配内存

🔹 作用 :当 vector 需要扩容时,reallocate(n) 进行 新内存分配、数据拷贝、释放旧内存 ,从而更新 capacity()

📌 示例

cpp 复制代码
#include <iostream>
#include <vector>

class MyVector {
private:
    int* _start;
    size_t _size;
    size_t _capacity;

    void reallocate(size_t new_capacity) {  
        int* new_start = new int[new_capacity]; // 分配新内存
        for (size_t i = 0; i < _size; i++) {
            new_start[i] = _start[i];  // 拷贝旧数据
        }
        delete[] _start; // 释放旧内存
        _start = new_start;
        _capacity = new_capacity;
    }

public:
    MyVector() : _start(nullptr), _size(0), _capacity(0) {}

    void push_back(int value) {
        if (_size == _capacity) {  // 触发扩容
            reallocate(_capacity ? _capacity * 2 : 1);
        }
        _start[_size++] = value;
    }

    void print() {
        for (size_t i = 0; i < _size; i++) {
            std::cout << _start[i] << " ";
        }
        std::cout << std::endl;
    }

    ~MyVector() { delete[] _start; } // 释放内存
};

int main() {
    MyVector vec;
    for (int i = 1; i <= 10; i++) {
        vec.push_back(i);
    }
    vec.print();
}

📌 输出

复制代码
1 2 3 4 5 6 7 8 9 10

reallocate() 触发 2x 扩容,拷贝旧数据,释放旧内存!


📌 3. allocate() vs reallocate()

函数 作用 拷贝旧数据? 释放旧内存? 使用场景
allocate(n) 分配新内存,不初始化 ❌ 否 ❌ 否 std::allocator 低级分配
reallocate(n) 重新分配内存,拷贝数据,释放旧内存 ✅ 是 ✅ 是 std::vector 动态扩容

allocate(n) 适用于手动内存管理,reallocate(n) 适用于动态数组扩容!

🚀 掌握 allocate()reallocate(),优化 C++ STL 容器! 🚀

相关推荐
持力行14 小时前
从C struct到C++中的class
c语言·c++
GIS阵地17 小时前
QgsRasterDataProvider 完整详解(QGIS 3.40.13 C++)
开发语言·c++·qt·开源软件·qgis
charlie11451419119 小时前
Cinux: 为大内核铺路
开发语言·c++·操作系统·现代c++
米罗篮21 小时前
矩阵快速幂 (Exponentiation By Squaring Applied To Matrices)
c++·线性代数·算法·矩阵
肖爱Kun21 小时前
C++设计策略模式
开发语言·c++·策略模式
炸膛坦客1 天前
单片机/C/C++八股:(二十四)编译文件( .bin 和 .hex ,包括 .elf 和 .axf )
c语言·c++·单片机
cpp_25011 天前
P10098 [ROIR 2023] 地铁建设 (Day 2)
数据结构·c++·算法·贪心·二分答案·洛谷题解
hehelm1 天前
IO 多路复用 — Reactor
linux·服务器·网络·数据库·c++
灵晔君1 天前
【C++】二叉搜索树
开发语言·c++
鱼子星_1 天前
【C++】内存管理:内存分布,new/delete的使用及细节处理,new/delete的底层,定位new表达式
开发语言·c++·笔记