Crash in VS2013 SP5 when inserting initializer_list into vector<string>

蹲街弑〆低调 提交于 2019-12-10 18:26:04

问题


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:


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.



来源:https://stackoverflow.com/questions/37062172/crash-in-vs2013-sp5-when-inserting-initializer-list-into-vectorstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!