Search code examples
c++constructorinitializer-listoverload-resolutionconstructor-overloading

Strange behavior of std::initializer_list of std::strings


This question is already asked most likely, but I did not find the answer.

The code below compiles with gcc but crashes at runtime, with std::length_error (live).

void test(const std::string &value) { std::cout << "string overload: " << value << std::endl; }

//void test(const std::vector<std::string> &) { std::cout << "vector overload" << std::endl; }

int main()
{
    test({"one", "two"});
}

The ability to create a string from the initializer list of strings seems controversial and, for example, does not make it possible to create the overload commented out in the code above.

But even if such construction is allowed, why does it lead to a failure?


Solution

  • It calls

    string(const char* b, const char* e) 
    

    string ctor overload.

    It works only if b and e points to the same string literal. Otherwise it is undefined behaviour.