gpt4 book ai didi

c++ - 是否可以捕获 std::call_once 中使用的函数的返回值?

转载 作者:行者123 更新时间:2023-12-02 01:37:58 58 4
gpt4 key购买 nike

假设我有一个函数返回一个昂贵的对象,并且我希望它在访问该函数的返回值时只调用一次。
这是可以通过 std::once_flagstd::call_once 实现的,还是我需要使用 bool 标志等?

简单的例子:

using namespace boost::interprocess;
shared_mempry_object openOrCreate(const char* name)
{
shared_memory_object shm(open_or_create, name, read_write);
return shm;
}

我有一种方法可以从某个例程调用此函数,并确保仅使用提到的原语调用一次,同时保持返回值?

最佳答案

只需使用静态函数变量即可。

using namespace boost::interprocess;
shared_mempry_object& openOrCreate(const char* name)
/// ^ return by reference to prevent copy.
{
static shared_memory_object shm(open_or_create, name, read_write);
// ^^^^^^ Make it static.
// This means it is initialized exactly once
// the first time the function is called.
//
// Because it is static it lives for the lifetime
// of the application and is correctly destroyed
// at some point after main() exits.

return shm; // return a fererence to the object
}

您可以添加一些包装器以保证在应用程序结束时进行清理。

关于c++ - 是否可以捕获 std::call_once 中使用的函数的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72036711/

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