c++c++11initializer-list

C++11 initializer_list error


Consider the code:

#include <iostream>
#include <vector>
#include <string>

int main()
{
    std::vector<std::string> v{{"awe", "kjh"}}; // not v{"awe", "kjh"}

    std::cout << v.size() << std::endl;

    return 0;
}
  1. Is this code erroneous? Or may be it is valid to use double {} while initializing vector?

  2. I tried this code on gcc and MSVC. MSVC 2012 + complier Nov 2012 just cannot compile it, it is not surprising. This code compiled with gcc 4.7 or 4.8 gives a runtime error during program execution. Is this behavour correct?

Unfortuantely can not test it with other compilers.


Solution

  • Note that your initialization is equivalent to:

    std::vector<std::string> v{std::string{"awe", "kjh"}}; 
    // not: std::vector<std::string> v{std::string{"awe"}, std::string{"kjh"}};
    

    The Standard does not require such a constructor of implementations of type std::string, so based on a particular STD implementation, I guess the code can do different things.

    Regards, &rzej