I am learning about std::vector
in C++. I learnt that a const std::vector<int>
means that we cannot change the individual elements within that vector and also cannot append/push_back more elements into it i.e., we only have read-access to the elements, which is expected from an entity that is a const
. But i find a difference when defining a const std::vector
than defining other const
types like int
, double
etc. The situation is shown below:
int main()
{
const int i; //doesn't compiler as expected: initializer needed here
const std::vector<int> vec1 ; //COMPILES FINE: WHY ISN'T AN INITIALIZER NEEDED HERE?
}
As we can see that for a const
built in type(like int
), we must provide an initializer.
My first question is that why isn't this the case for std::vector
. That is, how(why) are we allowed to omit the initializer for a const vector
. I mean the const vector
means that we won't be able to add elements into it so it seems that this vec1
is useless(practically) now.
So my second question is that is there a use for vec1
? I mean since the standard allows this so they may have already thought about this case and found out that this vec1
can be useful somewhere. That is, what are the use cases for this vec1
that had no initializer at the time of its definition.