RAII也常用于管理动态分配的内存,通过在对象构造函数中分配内存,在析构函数中释放内存。
- #include <iostream>
- #include <memory>
- class MemoryRAII {
- public:
- explicit MemoryRAII(size_t size) : data(new int[size]) {
- std::cout << "Memory allocated." << std::endl;
- }
- ~MemoryRAII() {
- delete[] data;
- std::cout << "Memory deallocated." << std::endl;
- }
- // 其他内存操作方法
- private:
- int* data;
- };
- int main() {
- try {
- MemoryRAII memory(10);
- // 在这里进行内存的读写操作,不用担心忘记释放内存
- } catch (const std::exception& e) {
- std::cerr << "Exception: " << e.what() << std::endl;
- }
- return 0;
- }
|