Crash in VS2013 SP5 when inserting initializer_lis

2019-07-03 05:01发布

Seeing a crash with the below code. I know initialize_lists have a poor reputation in VS, but I thought most of them were fixed with 2013 sp3. The same code works fine in g++ (6.1). Am I missing something here? This seems far too simple.

The debugger suggests a problem with an invalid iterator in the xstring module. The same code works find with integers, so I'm guessing it relates to some sort of string specific optimization.

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

int main(int argc, char** argv)
{
    std::vector<std::string> x = {"a","b","c","d"};

    for(auto i : x)
        std::cout << i << ":";
    std::cout << std::endl;

    x.insert(x.end(), {"e","f"});  // Crash here

    for(auto i : x)
        std::cout << i << ":";
    std::cout << std::endl;

    return 0;
}

1条回答
一纸荒年 Trace。
2楼-- · 2019-07-03 05:40

You would be surprised if you try inserting 3 elements like x.insert(x.end(), {"e","f", "g"});. No crash, right!

This is a bug in MSVC 2013 and seems to be fixed in MSVC 2015. Here is an explanation to shed some light to where the problem occurs. If you try only declaring std::string a{ "a", "b" }; you will see that it compiles fine but it causes a crash. If you add one more element, then it won't compile at all. So, what happens with the insert is that it calls the string constructor instead of calling vector constructor.

查看更多
登录 后发表回答