gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:07:17 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com