蓝色天空.知识 · 实践 · 创造
我的收藏
C++ 教程目录 99章
课程介绍
C++ / LEARN BY DOING

C++ 动态内存

详解 C++ 栈与堆内存分工、new/delete 与 malloc 的本质差异、一维/二维/三维动态数组与对象数组的对称释放,以及现代 C++17 unique_ptr/shared_ptr RAII 实践。

学完这一章,你能够

  • 详解 C++ 栈与堆内存分工、new/delete 与 malloc 的本质差异、一维/二维/三维动态数组与对象数组的对称释放,以及现代 C++17 unique_ptr/shared_ptr RAII 实践。

栈与堆分区及 new / delete 基础语义

C++ 程序的运行期内存核心区分栈(Stack)与堆(Heap / 自由存储区):函数内声明的局部自动变量位于栈上,随作用域自动创建与回收;当所需空间大小只能在运行时决定或对象需跨作用域存活时,则需借助 `new` 运算符在堆上动态分配地址,并在使用完毕后由 `delete` 归还。

`new data-type` 支持内置类型、数组以及自定义结构体/类。与 C 语言 `malloc()` 仅划拨原始字节不同,`new` 不仅分配内存还会自动调用对象构造函数,配对的 `delete` 会先调用析构函数再释放内存。注意:标准 `new` 在内存耗尽时默认抛出 `std::bad_alloc` 异常而非返回空指针;若想用判空分支检查分配失败,应显式使用 `new (std::nothrow)` 并以 `nullptr` 初始化与置空指针。

一维与多维动态数组的成对分配与释放

动态数组必须使用 `new T[n]` 分配并严格配对 `delete[] ptr` 释放(切勿混用单个 `delete`)。对于二维指针数组(如 4 行 8 列 `int** p`),需先分配外层指针数组 `new int*[m]`,再循环为每行分配 `new int[n]`;释放时必须严格按逆序先逐行 `delete[] p[i]`,最后再 `delete[] p`。

三维指针数组(如 `2×3×4` 的 `int*** p`)同理逐层分配,并由最内层向最外层逆序 `delete[]` 防止内存泄漏。在现代 C++ 工程中,除底层学习指针模型外,连续一维 `std::vector` 扁平化索引或嵌套 `std::vector` 通常具备更好的缓存局部性与异常安全保障。

对象数组生命周期对称性与现代智能指针

通过 `Box* myBoxArray = new Box[4];` 动态创建对象数组时,编译器会依次调用 4 次默认构造函数;调用 `delete[] myBoxArray;` 时则会按逆序调用 4 次析构函数再回收整块堆内存。现代 C++17 更推荐使用 `<memory>` 中的 `std::make_unique`(独占所有权、支持 `std::move` 转移)与 `std::make_shared`(引用计数共享所有权),借助 RAII 自动消除遗忘释放与异常路径泄漏风险。

验证标量 new/delete、1D/2D/3D 动态数组、Box[4] 构造/析构对称性及 unique_ptr/shared_ptr

含完整源码 · 127 行
展开查看收起
cpp
#include <iostream>
#include <memory>
#include <new>
#include <string>

struct TrackedBox {
    static int constructed;
    static int destroyed;
    int id = 0;

    TrackedBox() { ++constructed; }
    explicit TrackedBox(int v) : id(v) { ++constructed; }
    ~TrackedBox() { ++destroyed; }
};

int TrackedBox::constructed = 0;
int TrackedBox::destroyed = 0;

int main() {
    // 1. Scalar new/delete and nothrow new
    double* pvalue = new (std::nothrow) double(29494.99);
    int scaled = 0;
    if (pvalue != nullptr) {
        scaled = static_cast<int>((*pvalue) * 100.0 + 0.5);
        delete pvalue;
        pvalue = nullptr;
    }
    bool ok1 = (scaled == 2949499) && (pvalue == nullptr);

    // 2. Dynamic 1D, 2D (4x8), and 3D (2x3x4) arrays with matching delete[]
    int* arr1d = new int[5];
    int sum1d = 0;
    for (int i = 0; i < 5; ++i) {
        arr1d[i] = (i + 1) * 10;
        sum1d += arr1d[i];
    }
    delete[] arr1d;

    int** arr2d = new int*[4];
    for (int i = 0; i < 4; ++i) arr2d[i] = new int[8];
    int sum2d = 0;
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 8; ++j) {
            arr2d[i][j] = i * j;
            sum2d += arr2d[i][j];
        }
    }
    for (int i = 0; i < 4; ++i) delete[] arr2d[i];
    delete[] arr2d;

    int*** arr3d = new int**[2];
    for (int i = 0; i < 2; ++i) {
        arr3d[i] = new int*[3];
        for (int j = 0; j < 3; ++j) arr3d[i][j] = new int[4];
    }
    int sum3d = 0;
    for (int i = 0; i < 2; ++i) {
        for (int j = 0; j < 3; ++j) {
            for (int k = 0; k < 4; ++k) {
                arr3d[i][j][k] = i + j + k;
                sum3d += arr3d[i][j][k];
            }
        }
    }
    for (int i = 0; i < 2; ++i) {
        for (int j = 0; j < 3; ++j) delete[] arr3d[i][j];
        delete[] arr3d[i];
    }
    delete[] arr3d;

    std::string act2 = "s1=" + std::to_string(sum1d) + ",s2=" + std::to_string(sum2d) +
                       ",s3=" + std::to_string(sum3d);
    const std::string exp2 = "s1=150,s2=168,s3=72";
    bool ok2 = (act2 == exp2);

    // 3. Dynamic object array new Box[4] / delete[] calls 4 ctors & 4 dtors
    TrackedBox::constructed = 0;
    TrackedBox::destroyed = 0;
    TrackedBox* boxes = new TrackedBox[4];
    int mid_ctor = TrackedBox::constructed;
    int mid_dtor = TrackedBox::destroyed;
    delete[] boxes;
    std::string act3 = std::to_string(mid_ctor) + "/" + std::to_string(mid_dtor) + "->" +
                       std::to_string(TrackedBox::constructed) + "/" + std::to_string(TrackedBox::destroyed);
    const std::string exp3 = "4/0->4/4";
    bool ok3 = (act3 == exp3);

    // 4. Modern C++17 smart pointers: unique_ptr move & shared_ptr reference counting
    TrackedBox::constructed = 0;
    TrackedBox::destroyed = 0;
    long uc1 = 0, uc2 = 0, uc3 = 0;
    bool moved_empty = false;
    {
        auto u1 = std::make_unique<TrackedBox>(77);
        auto u2 = std::move(u1);
        moved_empty = (u1 == nullptr) && (u2 != nullptr) && (u2->id == 77);

        auto sp1 = std::make_shared<TrackedBox>(88);
        uc1 = sp1.use_count();
        {
            auto sp2 = sp1;
            uc2 = sp1.use_count();
        }
        uc3 = sp1.use_count();
    }
    std::string act4 = "mv=" + std::string(moved_empty ? "1" : "0") +
                       ",uc=" + std::to_string(uc1) + "-" + std::to_string(uc2) + "-" + std::to_string(uc3) +
                       ",cd=" + std::to_string(TrackedBox::constructed) + "/" + std::to_string(TrackedBox::destroyed);
    const std::string exp4 = "mv=1,uc=1-2-1,cd=2/2";
    bool ok4 = (act4 == exp4);

    std::cout << "{\n"
              << "  \"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\",\n"
              << "  \"cases\": [\n"
              << "    {\"name\": \"scalar_new_delete_and_nothrow\", \"expected\": true, \"actual\": "
              << (ok1 ? "true" : "false") << ", \"passed\": " << (ok1 ? "true" : "false") << "},\n"
              << "    {\"name\": \"dynamic_1d_2d_3d_arrays\", \"expected\": \"" << exp2
              << "\", \"actual\": \"" << act2 << "\", \"passed\": " << (ok2 ? "true" : "false") << "},\n"
              << "    {\"name\": \"object_array_ctor_dtor_symmetry\", \"expected\": \"" << exp3
              << "\", \"actual\": \"" << act3 << "\", \"passed\": " << (ok3 ? "true" : "false") << "},\n"
              << "    {\"name\": \"smart_pointers_unique_and_shared\", \"expected\": \"" << exp4
              << "\", \"actual\": \"" << act4 << "\", \"passed\": " << (ok4 ? "true" : "false") << "}\n"
              << "  ]\n"
              << "}\n";
    return 0;
}
在 G++ 13.3.0 C++17 离线容器中验证 nothrow new/delete、1D(150)/2D(168)/3D(72) 动态数组累加与逆序释放、new Box[4]/delete[] 4 次构造与 4 次析构对称及 unique_ptr 移动与 shared_ptr 引用计数 1->2->1->0 4 项全通过。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a2307.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:C++

课程关联工程包(登记关联99章) · 含当前章节或实例 · mbskycom202612a2307.zip

下载课程关联工程包:C++

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2320.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

标准 `new` 分配失败时会直接抛出 `std::bad_alloc` 异常,不会返回 `nullptr`;应当使用 `try/catch (const std::bad_alloc&)` 捕获异常,或显式写成 `new (std::nothrow) double` 后再判断返回值是否为 `nullptr`。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习