Thursday 3 May 2012

Schwarz counter in C++11 - std::call_once

Looking at the code below makes me think it would be trivial to implement a Schwarz counter using C++11 idioms

std::unique_ptr<some_resource> resource_ptr;
std::once_flag resource_flag;

void foo()
{
    std::call_once(resource_flag,[]{
        resource_ptr.reset(new some_resource);
    });
    resource_ptr->do_something();
}