简体   繁体   中英

Should I prefer to use a static class variable or a static variable inside a class method?

The question is, what would be the best or maybe a better practice to use. Suppose I have a function, which belongs to some class and this function needs to use some static variable. There are two possible approaches - to declare this variable as class's member:

class SomeClass
{
public:
    ....
    void someMethod();
private:
    static int m_someVar;
};

SomeClass::someMethod()
{
    // Do some things here
    ....
    ++m_someVar;
}

Or to declare it inside the function.

class SomeClass
{
public:
    ....
    void someMethod();
};

SomeClass::someMethod()
{
    static int var = 0;
    ++m_someVar;
    // Do some things here
    ....
}

I can see some advantages for the second variant. It provides a better encapsulation and better isolates details of an implementation. So it would be easier to use this function in some other class probably. And if this variable should be modified only by a single function, then it can prevent some erroneous data corruption from other methods.

While it's quite obvious, that the first variant is the only one to use when you need to share a static variable among several methods (class functions), the question pertains the case when a static variable should be used only for a single function. Are there any advantages for the first variant in that case? I can think only about some multi threading related stuff...

这很简单-如果在逻辑上它属于类(类似于instanceCounter ),则使用static成员;如果在逻辑上它属于函数( numberOfTimesThisMethodWasCalled ),则使用static本地。

The choice of static or not depends completely on the context. If a particular variable needs to be common among all the instances of a class, you make it static .

However, if a variable needs to be visible only in a function and needs to be common across every call of the function, just make it a local static variable.

The difference between static data members and static variable in a function is that first are initialized at start-up and the second first time the function is called (lazy initialization).

Lazy initialization can create problem when a function is used in a muti-threaded application, if it is not required by the design I prefer to use static members.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM