技术

现代 C++ 内存管理方法(Modern C++ Memory Management Summary)

现代 C++ 内存管理方法 Modern C++ Memory Management Summary

中文English
1. 传统手动内存管理(C++98/03)1. Manual Memory Management (C++98/03)
– 使用 new 和 delete 显式分配和释放内存。– Explicitly allocate and free memory with new and delete.
– 容易出现内存泄漏、悬空指针等问题。– Prone to memory leaks and dangling pointers.
2. 智能指针(C++11 起)2. Smart Pointers (Since C++11)
– 引入 <memory>,提供std::unique_ptr、std::shared_ptr和std::weak_ptr。– Introduced <memory> with std::unique_ptr, std::shared_ptr, and std::weak_ptr.
– 自动管理内存,防止泄漏,支持所有权语义。– Automatic memory management, ownership semantics, prevents leaks.
– unique_ptr 独占所有权,不能复制只支持移动。– unique_ptr has exclusive ownership, non-copyable but movable.
– shared_ptr 支持引用计数共享所有权。– shared_ptr supports shared ownership via reference counting.
3. 自动类型推断(C++11 起)3. Auto Type Deduction (Since C++11)
– 使用 auto 简化智能指针声明。– Use auto to simplify smart pointer declarations.
4. 右值引用与移动语义(C++11)4. Rvalue References and Move Semantics (C++11)
– 移动构造和移动赋值减少不必要拷贝,提高性能。– Move constructors and assignments reduce unnecessary copies, improve performance.
– 智能指针支持所有权移动,如std::move。– Smart pointers support ownership transfer with std::move.
5. 内存对齐与对齐分配(C++17)5. Memory Alignment and Aligned Allocation (C++17)
– 支持自定义对齐,提升性能,适用SIMD等场景。– Support custom alignment, improve performance, useful for SIMD and low-level code.
– 函数如 std::aligned_alloc。– Functions like std::aligned_alloc.
6. 多态内存资源管理(C++17)6. Polymorphic Memory Resource (PMR) (C++17)
– 通过 std::pmr 提供可定制的内存资源和分配器,优化性能。– Provides customizable memory resources and allocators via std::pmr to optimize performance.
7. C++20及以后内存模型与原子操作优化7. Memory Model and Atomic Operation Improvements (C++20 and beyond)
– 提升并发内存管理效率和安全性。– Enhances efficiency and safety of concurrent memory management.

示例代码 Examples

智能指针示例 Smart Pointer Example

#include <memory>

auto p1 = std::make_unique<int>(42);        // unique_ptr 独占所有权 Exclusive ownership

auto p2 = std::make_shared<int>(100);       // shared_ptr 引用计数 Shared ownership

auto p3 = std::move(p1);                     // 所有权转移 Ownership transfer

对齐分配示例 Aligned Allocation Example

#include <cstdlib>

void* ptr = std::aligned_alloc(64, 1024);   // 64 字节对齐,分配1024字节 Allocate 1024 bytes aligned to 64 bytes

std::free(ptr);

PMR示例 PMR Example

#include <memory_resource>

#include <vector>

std::pmr::monotonic_buffer_resource pool;

std::pmr::vector<int> vec(&pool);            // 使用自定义内存资源 Use custom memory resource