I have a class Foo
with no sensible default constructor. I would also prefer to keep the copy-assignment operator private, although that may become impossible. (I'd like to make the class “almost” immutable, whence thread-safe, by having const
fields and the small number of mutators that cast const way as private and early in the object lifetime.)
Creating std::vector<Foo>
under these constraints is a little bit of a challenge. I came up with a solution I haven't seen elsewhere (see, for example, earlier SO question 1). I have a custom iterator which, when dereferenced, creates a Foo
. It is set up such that each invocation increments to the next value of Foo
in the vector. The sequence is easy to define. I define operator++
, next
, advance
, distance
and operator*
on CustomIterator
.
Then I have
std::vector<Foo> foo_vec{CustomIterator(0), CustomIterator(size_of_vector)};
No access issues. No unnecessary constructions. No copies. Anyone see a problem with this?