3
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();
}
4

1 回答 1

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();
}
于 2012-11-08T11:16:27.937 回答