在C++中,可以在成员函数中使用静态变量,从而间接达到在hpp中定义属于某个类的静态变量的目的(无需再在cpp文件中初始化)
然而,这中方案在速度上会有一定的损耗。
1、该变量首次使用时才进行初始化
When do
function-level static variables get allocated/initialized?:https://stackoverflow.com/questions/55510/when-do-function-level-static-variables-get-allocated-initialized
2、每次使用都多出一个if语句及atomic操作(为了多线程安全性)
Does a function local static variable automatically incur a branch?https://stackoverflow.com/questions/23829389/does-a-function-local-static-variable-automatically-incur-a-branch
速度对比:
单线程调用1亿次,慢14ms左右
- static var use: 43ms
- static method var use: 67ms
class="c++" name="code">class TestStatic{
public:
static std::vector<int> v;
inline static std::vector<int>& mv(){
static std::vector<int> v;
return v;
}
};
std::vector<int> TestStatic::v;
void testStatic(){
int n=10000000;
int r=0;
int r2=0;
TestStatic::v.push_back(0);
TestStatic::mv().push_back(0);
LC::TimerAccurate timer;
for (int i=0;i<n;++i){
r+=TestStatic::v.size();
// TestStatic::v[0]++;
}
std::cout<<"static var use: \t"<<timer.getElapsedTime_in_ms()<<"ms"<<std::endl;
timer.restart();
for (int i=0;i<n;++i){
r2+=TestStatic::mv().size();
// TestStatic::mv()[0]++;
}
std::cout<<"static method var use: \t"<<timer.getElapsedTime_in_ms()<<"ms"<<std::endl;
timer.restart();
std::cout<<r<<std::endl;
std::cout<<r2<<std::endl;
std::cout << "End of test, " << __FUNCTION__ << std::endl;
exit(0);
}