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 容器! 🚀

相关推荐
夜悊1 小时前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴3 小时前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt00117 小时前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾20 小时前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you21 小时前
constexpr函数
c++
凡人叶枫1 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫1 天前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss1 天前
BRpc使用
c++·rpc
-森屿安年-1 天前
63. 不同路径 II
c++·算法·动态规划
chase_my_dream1 天前
Cartographer详细讲解
c++·人工智能·自动驾驶