RAII and C ++ STL

I have a case where I want to save a list of resources in std :: vector. As I can see, my options are as follows:

  • Give my resource a default constructor
  • Store them as heap objects (and wrap them in a generic pointer)

Option 1 allows you to build invalid resources, and option 2 forces me to use a bunch.

Am I missing any options here?

+5
source share
3 answers

You do not need a default constructor to have an instance vector.

The only limitation is that you cannot use vector :: resize with the default argument when the class does not have a default constructor.

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

but you can specify a vector :: resize object by default:

std::vector<foo> vec;
vec.resize(20, foo(10));  // give a sample object since foo has not default constructor
+7

constuctor . stl ( ).

+1

- Boost.PointerContainer. - . Johann, std::vector (), .

(, , - ..) . , , . , , , STL. Boost.PointerContainer . Boost.PointerContainer , .

+1

All Articles