Tuesday, November 14, 2023

C++ RAII- Resource Acquisition Is Initialization

C++ RAII- Resource Acquisition Is Initialization 

RAII (Resource Acquisition Is Initialization) is a C++ programming idiom that ties the lifecycle of a resource to the scope of an object. 

The basic idea behind RAII is to manage resources (like memory, file handles, network connections, etc.) automatically by tying their allocation and deallocation to the lifecycle of an object. When the object is created, the resource is acquired, and when the object goes out of scope, the resource is automatically released.


Here are the key principles of RAII:

Resource Acquisition

   - Resources (memory, file handles, sockets, etc.) are acquired during the initialization phase of an object. This is typically done in the constructor of the object.

Resource Release (Deallocation)

   - The resource is released or deallocated in the destructor of the object. This ensures that the resource is released when the object goes out of scope, regardless of how the scope is exited (normal exit, exceptions, etc.).

Initialization

   - The act of acquiring the resource is tied to the object's initialization. This ensures that the resource is properly acquired before the object is used.

Destruction

   - The act of releasing the resource is tied to the object's destruction. This ensures that the resource is released when the object is no longer needed, whether due to the normal flow of the program or exceptional conditions.


### Example:


Here's a simple example to illustrate the RAII principle, using dynamic memory allocation (new and delete):


```cpp

#include <iostream>


class MyResource {

public:

    MyResource() {

        // Acquire the resource (e.g., allocate memory)

        data = new int[10];

        std::cout << "Resource Acquired" << std::endl;

    }


    ~MyResource() {

        // Release the resource (e.g., deallocate memory)

        delete[] data;

        std::cout << "Resource Released" << std::endl;

    }


    // Other member functions can use the acquired resource


private:

    int* data;

};


int main() {

    {

        MyResource resource; // Resource is acquired in the constructor


        // Use the resource within this scope


    } // Resource is released when 'resource' goes out of scope


    // Resource is no longer accessible outside the scope


    return 0;

}

```

In this example, the `MyResource` class acquires a resource (an array of integers) in its constructor and releases it in its destructor. The scope of the object `resource` determines when the resource is acquired and released, adhering to the RAII principle.

No comments:

Post a Comment

LeetCode C++ Cheat Sheet June

🎯 Core Patterns & Representative Questions 1. Arrays & Hashing Two Sum – hash map → O(n) Contains Duplicate , Product of A...