面试题答案
一键面试#include <iostream>
#include <map>
#include <string>
#include <mutex>
template<typename T>
class TemplateClass {
public:
static std::map<std::string, int>& getStaticVar() {
static std::once_flag flag;
static std::map<std::string, int> staticVar;
std::call_once(flag, []() {
// 这里进行 staticVar 的初始化操作
staticVar["key1"] = 1;
staticVar["key2"] = 2;
});
return staticVar;
}
};
初始化方式
在 TemplateClass
中,通过 getStaticVar
函数来获取 staticVar
。getStaticVar
函数使用 std::once_flag
和 std::call_once
来确保 staticVar
只被初始化一次。在 std::call_once
的回调函数中,可以进行 staticVar
的初始化操作,比如向 std::map
中插入一些键值对。
线程安全性
在多线程环境下,std::once_flag
和 std::call_once
可以确保 staticVar
的初始化是线程安全的。std::call_once
会在首次调用时执行给定的回调函数,并且保证该回调函数在多线程环境下只被执行一次,从而避免了 staticVar
的重复初始化问题,确保了线程安全性。