Suppose I have a function returning an expensive object and I want it to call exactly once while having an access to return value of the function.
Is this achievable with std::once_flag
and std::call_once
or I need to go with boolean flags, etc..?
Simple example:
using namespace boost::interprocess;
shared_mempry_object openOrCreate(const char* name)
{
shared_memory_object shm(open_or_create, name, read_write);
return shm;
}
I there a way to call this function from some routine and ensure only calling once with mentioned primitives while maintaining return value?
CodePudding user response:
Simply use a static function variable.
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
}
You can add some wrapper to guarantee clean-up at the end of the application.