RAII

RAII (Resource Acquisition Is Initialization) is a programming technique used in C++ to manage resources automatically. It is a way to ensure that resources are properly acquired and released within the scope of an object's lifetime.
The basic idea behind RAII is that the acquisition of a resource is tied to the initialization of an object, and the release of the resource is tied to the destruction of that object. By encapsulating resource acquisition and release within an object's constructor and destructor, we can ensure that the resource is always properly managed, even in the presence of exceptions or early returns.

  1. Dynamic memory allocation:
// Using std::unique_ptr or std::shared_ptr to manage dynamically allocated memory:
std::unique_ptr<MyClass> uptr(new MyClass());
std::shared_ptr<MyClass> sptr(new MyClass());
// Use the object through the pointer
// When the unique_ptr/shared_ptr goes out of scope, the pointed-to object is automatically deleted.
  1. File handling
// Using std::ifstream and std::ofstream to open and close files
{
    std::ifstream file("input.txt");
    // Use the file
}
// File is automatically closed when the file object goes out of scope
  1. Mutex and Locks
// Using std::lock_guard or std::unique_lock to acquire and release mutexes:
{
    std::lock_guard<std::mutex> lock(my_mutex);
    // Critical section
}
// Mutex is automatically released when the lock_guard goes out of scope
  1. stl containers(vector, list, map)
  2. smart pointers(shared_ptr, unique_ptr, weak_ptr)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容