I am trying to initialize vector in constructor initializer list like so:
Foo::Foo()
: vec{42}
{
// ...
}
The vector is declared as:
std::vector<std::time_t> vec;
Problem is that std::time_t
is numeric type also, so instead of creating vector with 42 elements as I would like, it creates one element with stored value '42'.
Question: is there a way to initialize such vector with size in constructor initializer list?
When initialized with braced-init-list, the constructor of std::vector
taking std::initializer_list
is preferred; for vec{42}
it would initialize vec
as containing 1 element with value 42
.
You can apply parentheses initializer instead of braced-init-list (which is a C++11 feature).
Foo::Foo()
: vec(42) // initialize vec as containing 42 default-initialized elements
{
// ...
}