[ PROMPT_NODE_24598 ]
memory-performance
[ SKILL_DOCUMENTATION ]
# 内存管理与性能
## 智能指针
cpp
#include
// unique_ptr - 独占所有权
auto create_resource() {
return std::make_unique("data");
}
// shared_ptr - 引用计数
std::shared_ptr shared = std::make_shared(42);
std::weak_ptr weak = shared; // 非拥有引用
// 自定义删除器
auto file_deleter = [](FILE* fp) { if (fp) fclose(fp); };
std::unique_ptr file(
fopen("data.txt", "r"),
file_deleter
);
// enable_shared_from_this
class Node : public std::enable_shared_from_this {
public:
std::shared_ptr get_shared() {
return shared_from_this();
}
};
## 自定义分配器
cpp
#include
#include
// 用于固定大小对象的池分配器
template
class PoolAllocator {
struct Block {
alignas(T) std::byte data[sizeof(T)];
Block* next;
};
Block pool_[PoolSize];
Block* free_list_ = nullptr;
public:
using value_type = T;
PoolAllocator() {
// 初始化空闲链表
for (size_t i = 0; i next;
return reinterpret_cast(block->data);
}
void deallocate(T* p, size_t n) {
if (n != 1) return;
Block* block = reinterpret_cast(p);
block->next = free_list_;
free_list_ = block;
}
};
// 用法
std::vector<int, PoolAllocator> vec;
// Arena 分配器 - 线性分配器
class Arena {
std::byte* buffer_;
size_t size_;
size_t offset_ = 0;
public:
Arena(size_t size) : size_(size) {
buffer_ = new std::byte[size];
}
~Arena() {
delete[] buffer_;
}
template
T* allocate(size_t n = 1) {
size_t alignment = alignof(T);
size_t space = size_ - offset_;
void* ptr = buffer_ + offset_;
if (std::align(alignment, sizeof(T) * n, ptr, space)) {
offset_ = size_ - space + sizeof(T) * n;
return static_cast(ptr);
}
throw std::bad_alloc();
}
void reset() {
offset_ = 0;
}
};
## 移动语义