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:
Option 1 makes it possible to construct invalid resources and option 2 forces me to use the heap.
Am I missing any options here?
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.
Resource acquisition is initialization (RAII) is a programming idiom used in several object-oriented, statically-typed programming languages to describe a particular language behavior.
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 ...
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With