---
title: "C++函数中的静态变量"
author: "cherishLC"
date: "2019-07-19T11:22:54Z"
tags: ["C++"]
categories: ["编程语言"]
slug: "c"
draft: false
lastmod: "2019-07-19T11:22:53Z"
id: 2442799
url: "https://cherishlc.iteye.com/blog/2442799"
---

在C++中，可以在成员函数中使用静态变量，从而间接达到在hpp中定义属于某个类的静态变量的目的（无需再在cpp文件中初始化） 然而，这中方案在速度上会有一定的损耗。 \[b]1、该变量首次使用时才进行初始化\[/b] When do function-level static variables get allocated/initialized?：\[url]https://stackoverflow.com/questions/55510/when-do-function-level-static-variables-get-allocated-initialized\[/url] \[b]2、每次使用都多出一个if语句及atomic操作（为了多线程安全性） \[/b] Does a function local static variable automatically incur a branch?\[url]https://stackoverflow.com/questions/23829389/does-a-function-local-static-variable-automatically-incur-a-branch\[/url] \[b]速度对比： \[/b] 单线程调用1亿次，慢14ms左右 \[list] \[\*]static var use: 43ms \[\*]static method var use: 67ms \[/list] \[code="c++"]class TestStatic{ public: static std::vector v; inline static std::vector& mv(){ static std::vector v; return v; } }; std::vector 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