Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RAII and C++ STL

Tags:

c++

stl

raii

I have a case where I wish to store a list of resources in a std::vector. As I see it, my options are as follows:

  1. Give my resource a default constructor
  2. Store them as heap objects (and wrap them in a shared pointer)

Option 1 makes it possible to construct invalid resources and option 2 forces me to use the heap.

Am I missing any options here?

like image 829
Dirk Avatar asked Mar 05 '10 07:03

Dirk


People also ask

Does C have RAII?

C does not have RAII-like memory management in any way. Exceptions work beautifully with memory management like that, but if it's not there, you can't just say it should work because memory management should work like that.

What does RAII stand for?

Resource acquisition is initialization (RAII) is a programming idiom used in several object-oriented, statically-typed programming languages to describe a particular language behavior.

What does RAII do?

Resource Acquisition Is Initialization or RAII, is a C++ programming technique which binds the life cycle of a resource that must be acquired before use (allocated heap memory, thread of execution, open socket, open file, locked mutex, disk space, database connection—anything that exists in limited supply) to the ...

What is RAII object in C++?

The principle that objects own resources is also known as "resource acquisition is initialization," or RAII. When a resource-owning stack object goes out of scope, its destructor is automatically invoked. In this way, garbage collection in C++ is closely related to object lifetime, and is deterministic.


1 Answers

You don't need a default constructor to have a vector of instances.

The only limitation is you can't use vector::resize with the default argument when the class has no default constructor.

vec.resize(20);  // requires default constructor

but you can give vector::resize a default object:

std::vector<foo> vec;
vec.resize(20, foo(10));  // give a sample object since foo has not default constructor
like image 152
R Samuel Klatchko Avatar answered Sep 18 '22 06:09

R Samuel Klatchko