Questions tagged [raii]

Resource Acquisition Is Initialization (RAII) is a common idiom used in C++ to manage the lifetime of resources, including memory allocations, file handles or database connections. In brief, every resource should be wrapped in an owning class, whose lifetime controls the lifetime of the resource.

Wikipedia

Resource Acquisition Is Initialization (RAII) is a programming idiom used in several object-oriented languages, most prominently C++, where it originated, but also D, Ada, Vala, and Rust. The technique was developed for exception-safe resource management in C++ during 1984–89, primarily by Bjarne Stroustrup and Andrew Koenig, and the term itself was coined by Stroustrup.

Basic Example

The most basic example of RAII may look like this:

struct intarray {
  explicit intarray (size_t size) : array(new int[size]) {}
  ~intarray (){ delete[] array; }

  int& operator[](size_t idx) { return array[idx]; }
  const int& operator[] const (size_t idx) { return array[idx]; }

private:
  intarray (const intarray &);
  intarray & operator=(const intarray&);

  int* const array;
};

This class encapsulates a memory allocation (for an array of int), so that when the intarray class is created, it creates a resource (the memory allocation), and when it is destroyed, it destroys the resource.

A user of the class can now write code such as this to create an array whose size is determined at runtime:

void foo(size_t size) {
  intarray myarray(size);
  // no bounds checking in this example: assume that size is at least 15
  myarray[10] = 0;
  myarray[14] = 123;
}

This code will not leak memory. myarray is declared on the stack, so it is automatically destroyed when we leave the scope in which it was declared; when foo returns, myarray's destructor is called. And myarray's destructor internally calls delete[] on the internal array.

We can write a more subtle version of the function, which also will not leak memory:

void foo(size_t size) {
  intarray myarray(size);
  bar();
}

We know nothing about bar's behavior (although we assume that it will not leak memory), so it is possible that it may throw an exception. Because myarray is a local variable, it is still automatically destroyed, and so it will implicitly also release the memory allocation it was responsible for.

Without using RAII, we would have had to write something like this to ensure that no memory leaks could occur:

void foo(size_t size) {
  int* myarray = new int[size];
  try {
    bar();
    delete[] myarray;
  }
  catch (...){
    delete[] myarray;
    throw;
  }
}

By relying on RAII, we no longer have to write implicit cleanup code. We rely on the automatic lifetime of local variables to clean up their associated resources.

Note that in this simple example, the copy constructor and assignment operator were both declared private, giving us a class that can not be copied. If this had not been done, care would have to be taken in their implementation to ensure that the resource is only freed once. (A naive copy constructor would simply copy the array pointer from the source object, resulting in two objects holding a pointer to the same memory allocation, and so both will try to release it when their destructors are called).

Common solutions are either to use a reference counting scheme (so that the last object to be deleted will also be the one who finally deletes the shared resource), or simply cloning the resource when the RAII wrapper is copied.

RAII in the Standard Library

RAII is widely used in the C++ standard library. The container classes, such as std::vector employ RAII to control the lifetime of the objects they store, so that the user does not have to keep track of allocated memory. For example,

std::vector<std::string> vec;
std::string hello = "hello";
vec.push_back(hello);

contains numerous memory allocations:

  • the vector allocates an internal array, conceptually similarly to the intarray class described above,
  • a string is created, containing a dynamically allocated buffer storing the text "hello",
  • a second string is allocated in the vector's internal buffer, and this string also creates an internal buffer to store its data. The data from the first string is copied into the second string.

And yet, as library users, we did not have to call new even once, and nor do we need to call delete or worry about cleanup. We created our objects on the stack, where they are automatically destroyed when they go out of scope, and they take care of their memory allocations internally. Even when we copy from one string to another, the string implementation takes care of copying the internal buffers, so that each string owns a separate copy of the string "hello".

And when the vector goes out of scope, it takes care of destroying every object stored in it (which, in turn, is responsible for releasing its internal memory allocation), before releasing its internal buffer.

The standard library also employs RAII to manage other resources, such as file handles. When we create a file stream, it is a RAII wrapper class which takes ownership of the file handle used internally. So when the file stream is destroyed, the file handle is closed and destroyed as well, allowing us to write code like this:

void foo() {
    std::ofstream("file.txt") << "hello world";
}

Again, we create an object (in this case an output file stream), which internally allocates one or more resources (it acquires a file handle, and very likely also performs one or more memory allocations for internal buffers and helper objects), and as long as the object is in scope, we use it. Once it goes out of scope, it automatically cleans up every resource it acquired.

Smart pointers

Many people equate RAII with the use if common smart pointer classes, which is an oversimplification. As the previous two examples, RAII can be used in many cases without relying on a smart pointer class.

A smart pointer is an object with the same interface as a pointer (sometimes with minor restrictions), but which takes ownership of the object it points to, so that the smart pointer takes responsibility for deleting the object it points to.

The Boost library contains several widely used smart pointers:

  • boost::shared_ptr<T> implements reference counting, so that while many shared_ptr's may point to an object of type T, the last one to be destroyed is responsible for deleting the pointed-to object.
  • boost::scoped_ptr<T> has some similarity to the intarray example, in that it is a pointer that cannot be copied or assigned to. It is given ownership of an object at creation, and will, when it goes out of scope, destroy that object.

The C++ standard library contains a std::auto_ptr<T> (superseded in C++11 by std::unique_ptr<T>), which, like scoped_ptr allows only one pointer to own an object, but unlike it, also allows this ownership to be transferred, so that the original pointer loses ownership of the object, and the new pointer gains it. The original pointer then becomes a null pointer which does nothing when it is destroyed.

596 questions
0
votes
3 answers

How to design a QObject that manages its own lifetime safely

I am implementing a class Exporter to perform some export actions. This class derives from QObject. I want to create a pointer to that class on the heap from a const function of the class C (C::triggerExport). I cannot create a unique_ptr as a…
Llopeth
  • 406
  • 5
  • 11
0
votes
0 answers

Is virtual destructor in base class needed when all destructors are default

I understand that we should use virtual destructors in base classes to ensure proper resource disposal, because it guarantees the inheritance chain will be observed and all parent destructors will be called when destructing an object. That being…
Jackson
  • 559
  • 7
  • 20
0
votes
3 answers

C++: ways to free a dynamic array (member of a struct) and a pointer to this struct

all. Suppose we have pointer to a struct, which has a member that is a dynamic array (among other members). I can free all the objects but want your opinion on the best practice for this specific situation. See the code below, that compiles and runs…
JayY
  • 109
  • 10
0
votes
1 answer

RAII std::vector design conundrum

I’m not a fan of classes like the one below that have an IsValid() function, because you have to remember to check IsValid() everywhere: struct BadTextWidget { BadTextWidget(const std::string & TEXT) : m_text(TEXT) {} bool IsValid() const; …
Til
  • 11
  • 3
0
votes
0 answers

Tiny RAII for tests of snippets

At the moment I'm on Windows and I work with WinAPI. I do not like try\catch so I use RAII, and this is construction which I usually use: #define r_free(N, T, F, n) \ struct N { \ T res; \ N()…
user9171470
0
votes
1 answer

How does Rust enforce/implement RAII

I'm working on a (maybe) serious programming language and want to learn about implementing memory management. I want this language to enforce RAII, similar to Rust, but, unlike rust, this language is Object-Oriented and I hope I can implement…
0
votes
1 answer

Copying RAII object in C++

I am reading Effective C++, in Rule 14: Think carefully about copying behavior in resource-managing classes, there is an example: class Lock { public: explicit Lock(Mutex* pm) : mutexPtr(pm) { lock(mutexPtr); } ~Lock() { …
Caesium
  • 789
  • 3
  • 7
  • 24
0
votes
1 answer

assignment fails for a FILE* class

I tried to wrap class around FILE*, here it is class file_ptr { public: file_ptr(const wstring& _FileN, const wstring& _OpenMode) : file_n(_FileN), omode(_OpenMode), fptr(_wfopen(file_n.c_str(), omode.c_str())) { …
unknown.prince
  • 710
  • 6
  • 19
0
votes
2 answers

How to delete nested new in C++

In ref, they have this line of code Widget *aWidget = new BorderDecorator(new BorderDecorator(new ScrollDecorator (new TextField(80, 24)))); Two questions: Say, I want to explicitly delete the objects created with new. How do you do that? BTW,…
beginner 101
  • 163
  • 5
0
votes
0 answers

Constructor call of class holding a RAII class causes segmentation fault

I'm new and I'm learning c++ and a bit of the SFML. To test what my studies I started consulting the "SFML game development" book, from wich I got the ResourceHolder in the code. The problem is that when I try to implement it the code does compile…
Eno
  • 1
  • 2
0
votes
0 answers

If an Object allocates dynamic memory from the heap, then how to design a destructor without some unwanted side effect?

So this is how the object looks like. A simple variable length array with an upper bound on the size. class Queue {public: int *array; unsigned siz;//Indicates how many elements are there right now void print() const; …
Della
  • 1,264
  • 2
  • 15
  • 32
0
votes
1 answer

End of lifetime of static object at block scope versus global scope

In this passage on program exit from cppreference.com If the completion of the constructor or dynamic initialization for thread-local or static object A was sequenced-before thread-local or static object B, the completion of the destruction of B is…
John McFarlane
  • 5,528
  • 4
  • 34
  • 38
0
votes
1 answer

How to prevent a temporary from going out of scope?

In the following case my object goes out of scope and I access an invalid pointer: struct Animal { char* buffer; Animal() { buffer = new char[100]; } ~Animal() { delete[]buffer; } }; int main() { vector list; { …
Zebrafish
  • 11,682
  • 3
  • 43
  • 119
0
votes
0 answers

UT friendly singleton - is there a flaw in my reasoning?

There is a need in my project for a registry that would hold some states and that could be easily accesible from anywhere in the code. Singleton is something we already use in a classic implementation static X& X::instance() { …
Marcin K.
  • 683
  • 1
  • 9
  • 20
0
votes
2 answers

How to implement RAII + lazy initialization?

Is it possible to implement in C++ a design that is both - RAII, to ensure the resource is safely released, and - lazy initialzation, that the resource is acquired only when it's really used. My idea is that just implement as a lazy initialization,…
athos
  • 6,120
  • 5
  • 51
  • 95