为什么这个程序 运行 在 Clang 或 GCC 下不能正常运行?

Why doesn't this program run properly under Clang or GCC?

我正在尝试 运行 CPPReference's regex_search example:

#include <iostream>
#include <string>
#include <regex>

int main()
{
    std::string lines[] = {"Roses are #ff0000",
                           "violets are #0000ff",
                           "all of my base are belong to you"};

    std::regex color_regex("#([a-f0-9]{2})"
                        "([a-f0-9]{2})"
                        "([a-f0-9]{2})");

    for (const auto &line : lines) {
        std::cout << line << ": " 
                  << std::regex_search(line, color_regex) << '\n';
    }   

    std::smatch color_match;
    for (const auto &line : lines) {
        std::regex_search(line, color_match, color_regex);
        std::cout << "matches for '" << line << "'\n";
        for (size_t i = 0; i < color_match.size(); ++i)
            std::cout << i << ": " << color_match[i] << '\n';
    }   
}

此程序使用 Clang++ 3.4-1ubuntu3 和 GCC 4.8.2 编译,但 运行立即给出此错误:

terminate called after throwing an instance of 'std::regex_error'
  what():  regex_error
Aborted (core dumped)

This question 表示问题出在 GCC 上,但用 Clang 编译也会出现同样的问题。甚至在每一步使用命令显式传递库:

clang++ -stdlib=libstdc++ -std=c++11 -H -c regex.cpp -o object.o && clang++ -stdlib=libstdc++ object.o -o regex

在 运行 时导致错误,尽管第一个命令输出的最后几行是:

.. /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/regex_constants.h
.. /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/regex_error.h
.. /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/regex_cursor.h
.. /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/regex_nfa.h
... /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/regex_nfa.tcc
.... /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/regex
.. /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/regex_compiler.h
.. /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/regex_grep_matcher.h
... /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/regex_grep_matcher.tcc
.... /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/regex
.. /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/regex.h

...这表明我的系统中存在适当的 headers。

您仍然使用不完整的 gcc 标准库实现,您甚至明确告诉 clang 将其与 -stdlib=libstdc++ 一起使用。

clang 附带的标准库实现是 libc++,因此您需要 -stdlib=libc++