鉴于此处的代码:
class lazy_init
{
mutable std::once_flag flag;
mutable std::unique_ptr<expensive_data> data;
void do_init() const
{
data.reset(new expensive_data);
}
public:
expensive_data const& get_data() const
{
std::call_once(flag,&lazy_init::do_init,this);
return *data;
}
};
我在其他地方也看到了相同模式的一些变体。所以我的问题是:为什么这段代码被认为是保存?为什么编译器不能在调用 std::call_once 之前读取数据并最终得到不正确的数据?例如
tmp = data.get();
std::call_once(flag,&lazy_init::do_init,this);
return *tmp;
我的意思是我没有发现任何可以阻止这种情况的障碍。