将lambdas放在静态初始化列表中并通过引用捕获是否安全?

时间:2012-11-08 10:38:35

标签: c++ reference static lambda initializer-list

void func(const std::string& args)
{

    // Statically initialize a vector of lambdas (only one here for now)
    // The lambdas capture by reference with[&], but since the
    // initializer list is static (and thus initialized only once), how
    // will the lambda be able to access args with each successive call to func()?
    // Won't there be undefined behavior with this?
    static std::vector<std::function<void()>> FuncMap =
    {

        // args (and everything else in scope) will be captured by reference
        { [&]() { for(const auto& s: args) std::cout << s << std::endl; }}

    };

    auto f = FuncMap[0];

    f();
}

1 个答案:

答案 0 :(得分:1)

我不知道你是出于好奇而问这个问题,还是你真的想要做这样的事情。如果是后者,这是一个可能的解决方案:

void func(const std::string& args)
{
    static std::string const * pargs;
    static std::vector<std::function<void()>> FuncMap =
    {        
        { [&]() { for(const auto& s: *pargs) std::cout << s << std::endl; }}
    };

    pargs = &args;
    auto f = FuncMap[0];

    f();
}