centos

CentOS C++内存管理如何做

小樊
37
2025-12-09 15:40:28
栏目: 编程语言

CentOS 下 C++ 内存管理实践指南

一 核心原则与编码规范

二 分配策略与性能优化

三 检测分析与问题定位

四 运行时环境与系统调优

五 最小示例与落地清单

#include <memory>
#include <vector>
#include <string>

struct Foo {
    std::string name;
    explicit Foo(std::string n) : name(std::move(n)) {}
};

// 独占所有权:unique_ptr + make_unique
auto p = std::make_unique<Foo>("demo");

// 共享所有权:shared_ptr/weak_ptr 组合
auto sp1 = std::make_shared<Foo>("shared");
std::weak_ptr<Foo> wp = sp1;
if (auto sp2 = wp.lock()) {
    // 使用 sp2
}

// 容器自动管理内存
std::vector<std::unique_ptr<Foo>> foos;
foos.push_back(std::make_unique<Foo>("a"));
foos.push_back(std::make_unique<Foo>("b"));
// 离开作用域自动释放

0
看了该问题的人还看了