atomic<int> cnt=0;
int get_int() noexcept
{
cnt++;
return rand();
}
然後:
void func()
{
static const auto value = get_int();
}
我知道會有對value
初始化無競爭狀態,但我不知道是否 get_int()
將被調用一次,或在我的示例中cnt
將爲1(而不是2,3,4或5)。
假設多個線程輸入func()
和get_int
只有1個呼叫站點在func()
。
如果擔心多個線程同時調用'func',我想你可以使用類似'std :: call_once([] {cnt ++;});' – chris 2014-11-05 14:50:38
cnt只是一個例子,我其實很擔心泄漏因爲我真正的get_int函數實際上返回指向它分配的對象的指針。 – NoSenseEtAl 2014-11-05 14:57:57