🍏对象生存期和资源管理|RAII设计思想
引出RAII
RAII 的好处
一些自定义的RAII类
1. 内存管理
#include <iostream>
#include <cstring>
class MemoryBlock {
public:
MemoryBlock(size_t size) {
data_ = new char[size]; // 分配内存
size_ = size;
std::cout << "MemoryBlock of size " << size << " allocated." << std::endl;
}
~MemoryBlock() {
delete[] data_; // 释放内存
std::cout << "MemoryBlock of size " << size_ << " deallocated." << std::endl;
}
// 禁止拷贝
MemoryBlock(const MemoryBlock&) = delete;
MemoryBlock& operator=(const MemoryBlock&) = delete;
// 允许移动
MemoryBlock(MemoryBlock&& other) noexcept : data_(other.data_), size_(other.size_) {
other.data_ = nullptr;
other.size_ = 0;
}
MemoryBlock& operator=(MemoryBlock&& other) noexcept {
if (this != &other) {
delete[] data_;
data_ = other.data_;
size_ = other.size_;
other.data_ = nullptr;
other.size_ = 0;
}
return *this;
}
char* data() { return data_; }
size_t size() const { return size_; }
private:
char* data_;
size_t size_;
};
int main() {
MemoryBlock block1(1024); // 分配1KB的内存块
MemoryBlock block2(2048); // 分配2KB的内存块
// 将block1的资源转移到block3
MemoryBlock block3(std::move(block1));
return 0;
}2. 线程锁管理
3. 文件描述符管理
4. 网络资源管理
5. 临时文件管理
reference
Last updated