Lambda使用的静态变量未初始化

用户名

我试图在这样的lambda中使用静态变量

void scrape_link(const std::string& url, std:function<void()> callback)
{
    static const std::regex link_match { 
        R"re(href="([^"]+)")re",
        std::regex_constants::optimize
    };

    async_download(url,[callback=std::move(callback)] (std::vector<char>& data)
    {
        std::smatch matches;
        if(std::regex_search(data.begin(), data.end(), matches, link_match))
            std::cout << matches[1] << std::endl;
        callback();
    });
}

当我编译不带-O3标志的代码时,我似乎没有遇到任何问题。它按预期工作。但是,打开该标志后,正则表达式搜索每次都会失败。我怀疑该link_match对象未正确初始化。任何想法如何解决这个问题?

请注意,lambda是从另一个线程异步调用的。

更新:似乎是编译器问题。我是在gcc 6.2上编译的。我在gcc 7.2中没有观察到此问题。

迈克尔·罗伊

乍一看,这似乎是编译器错误。link_match不能在其直接范围内使用,这可能会使优化器感到困惑。解决方法:

void scrape_link(const std::string& url, std:function<void()> callback)
{
    static const std::regex link_match { 
        R"re(href="([^"]+)")re",
        std::regex_constants::optimize
    };

    // force the creation of link_match by using it in the capture clause.

    async_download(url,[&link_match, callback=std::move(callback)] (std::vector<char>& data)
    {
        std::smatch matches;
        if(std::regex_search(data.begin(), data.end(), matches, link_match))
            std::cout << matches[1] << std::endl;
        callback();
    });
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章