Skip to main content

Posts

Showing posts with the label RAII

[C++] Handling Exceptions in Constructors

When you use RAII idiom, there are often situations where constructors have to do complex tasks. These complex tasks can sometimes fail, resulting in throwing exceptions. This raises a concern: Is it okay to throw exceptions in constructors? The first concern is memory leaks. Fortunately, memory leaks do not occur. Variables created on the stack are released through stack unwinding, and if an exception occurs during heap allocation with the new operator, the new operator automatically deallocates the memory and returns nullptr . The next concern is whether the destructor of the member variables will be called correctly. However, this is also not a problem. When an exception occurs, member variables can be divided into three categories: fully initialized member variables, member variables being initialized, and uninitialized member variables. Fully initialized member variables have had their constructors called and memory allocations completed successfully. In the example code, t...

What Is RAII

RAII is a frequently used idiom in C++ that ensures the safe usage of resources by releasing them when an object's scope ends. In C++, resources allocated on the heap are not released unless explicitly done so, but those allocated on the stack are automatically released when their scope ends, triggering their destructor. Originally, RAII was used to guard against unexpected changes in control flow, such as exceptions. In the above code example, the unsafeFunction() function is not safe. If the thisFunctionCanThrowException() throws an exception, the resource may not be released. The unmaintanableFunction releases the resource , but it is not easy to read and maintain. The safeFunction example uses unique_ptr , a smart pointer introduced at C++11, for RAII. unique_ptr automatically releases the memory it holds when it is destroyed, ensuring that the resource is released when the function exits. The resource does not only refer to heap memory but also includes files, d...