Search code examples
c++initializationstdvectorstdstringlist-initialization

What does std::vector<std::string> vec{3}; actually do?


I am currently trying to understand list initialization in C++11 and I have stumbled upon this line of code: std::vector<std::string> vec{3}; I am wondering what it is actually doing, I noticed 3 elements are created in the vector however, I am not sure why and what values these elements will be initialized with.

Edit: I have tried running:

int main()
{
  std::vector<std::string> vec{3};
  std::cout<<vec.size()<<std::endl;
  std::cout<<vec[0]<<std::endl;
  std::cout<<vec[1]<<std::endl;
  std::cout<<vec[2]<<std::endl;
}

and I only get the output:
3

If they are default initialized shouldn't the output be:
3
0
0
0


Solution

  • vector<T> has a constructor which takes a single integer; it creates a vector containing 3 default-initialized Ts. This constructor is therefore a viable candidate constructor when you use syntax equivalent to vector<T>{3}.

    However, the use of {} syntax means that any vector<T> constructors which take an initalizer_list are checked first. If the T in vector<T> was an integer type, {3} would map to vector<T>'s initializer_list<T> constructor.

    But since T in this case is a std::string, vector<std::string>'s initializer_list constructor doesn't match an integer. So instead, the N-element constructor is called.

    To avoid such things in the future, you should avoid using {} with containers and container-like types unless your intent is to initialize them with a sequence of elements.

    If they are default initialized shouldn't the output be:

    No. A default-initialized std::string contains no characters. Not the "0" character, no characters. If you print out a string containing no characters, then you have printed out nothing.