我知道这是一个经常被问到的问题,但由于有很多变种,我想重新陈述它,并希望有一个反映当前状态的答案.就像是
Logger& g_logger() {
static Logger lg;
return lg;
}
Run Code Online (Sandbox Code Playgroud)
变量lg的构造函数是否保证只运行一次?
我从以前的答案中知道,在C++ 03中,这不是; 在C++ 0x草案中,这是强制执行的.但我想要一个更明确的答案
我写了以下玩具示例:
std::map<char, size_t> getMap(const std::string& s)
{
std::map<char, size_t> map;
size_t i = 0;
for (const char * b = s.data(), *end = b + s.size(); b != end; ++b)
{
map[*b] = i++;
}
return map;
}
void check(const std::string& s)
{
//The creation of the map should be thread safe according to the C++11 rules.
static const auto map = getMap("12abcd12ef");
//Now we can read the map concurrently.
size_t n = 0;
for (const char* b = s.data(), …Run Code Online (Sandbox Code Playgroud) 以下函数是否是线程安全的?如果它不是线程安全的,那么实际上是否有任何开销使funImpl非静态?或者编译器是否实际内联函数对象函数并完全跳过创建函数对象?
int myfun(std::array<int, 10> values)
{
static const auto funImpl = [&]() -> int
{
int sum = 0;
for (int i = 0; i < 10; ++i)
{
sum += values[i];
}
return sum;
};
return funImpl();
}
Run Code Online (Sandbox Code Playgroud)
编辑:我编辑了以下功能签名:
int myfun(const std::array<int, 10>& values)
Run Code Online (Sandbox Code Playgroud)
至:
int myfun(std::array<int, 10> values)
Run Code Online (Sandbox Code Playgroud)
所以我很清楚我不是在询问值的踏板安全性,而是函数局部静态变量funImpl的线程安全性.