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

标签 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();
}

最佳答案

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

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

关于c++ - 将 lambda 放在静态初始化列表中并通过引用捕获是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13287339/

相关文章:

c++ - 一元和二元否定

c++ - 友元和运营商=重载

c++ - 输入流的 std::setfill 和 std::setw ?

.net 引用特定版本是真是假?

inheritance - F# 静态覆盖

c++ - 如何保存和加载文本模式游戏

Java:方法似乎是通过引用传递的

Javascript双向引用问题

c++ - dos.h 是一个什么样的库(静态的还是动态的)?

c++ - 不完整类型的静态字段 - 合法吗?