linux

Linux中C++如何进行动态内存分配

小樊
44
2025-06-17 19:56:03
栏目: 编程语言

在C++中,动态内存分配通常使用newdelete操作符(对于单个对象)或new[]delete[]操作符(对于对象数组)来完成。这些操作符允许你在程序运行时请求内存,并在不再需要时释放它。

以下是一些基本的示例:

单个对象的动态内存分配

#include <iostream>

int main() {
    // 动态分配一个int类型的对象
    int* ptr = new int;

    // 使用指针
    *ptr = 42;
    std::cout << "The value of the integer is: " << *ptr << std::endl;

    // 释放内存
    delete ptr;

    return 0;
}

对象数组的动态内存分配

#include <iostream>

int main() {
    // 动态分配一个int类型的对象数组,包含5个元素
    int* arr = new int[5];

    // 使用数组
    for (int i = 0; i < 5; ++i) {
        arr[i] = i * i;
        std::cout << "arr["<< i << "] = " << arr[i] << std::endl;
    }

    // 释放内存
    delete[] arr;

    return 0;
}

使用智能指针进行自动内存管理

为了避免手动管理内存(如忘记释放内存导致的泄漏),C++11引入了智能指针,如std::unique_ptrstd::shared_ptr。它们提供了自动内存管理功能。

使用std::unique_ptr

#include <iostream>
#include <memory>

int main() {
    // 使用std::unique_ptr动态分配一个int类型的对象
    std::unique_ptr<int> ptr = std::make_unique<int>(42);

    // 使用指针
    std::cout << "The value of the integer is: " << *ptr << std::endl;

    // 不需要手动释放内存,std::unique_ptr会在离开作用域时自动释放

    return 0;
}

使用std::shared_ptr

#include <iostream>
#include <memory>

int main() {
    // 使用std::shared_ptr动态分配一个int类型的对象
    std::shared_ptr<int> ptr = std::make_shared<int>(42);

    // 使用指针
    std::cout << "The value of the integer is: " << *ptr << std::endl;

    // 不需要手动释放内存,std::shared_ptr会在最后一个引用离开作用域时自动释放

    return 0;
}

使用智能指针可以大大简化内存管理,并减少内存泄漏的风险。

0
看了该问题的人还看了