Search code examples
c++stlraii

RAII and C++ STL


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?


Solution

  • 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