简体   繁体   English

函数内部的静态变量与c ++中的静态类变量

[英]static variable inside function vs static class variable in c++

For a unique id for some object I can create a counter in two ways but I don't know which one is better while they are quite different in code (though maybe not in byte code, I have no idea). 对于某个对象的唯一id,我可以用两种方式创建一个计数器,但我不知道哪一个更好,而它们在代码上完全不同(尽管可能不是字节代码,我不知道)。

The first way would be to have some function which uses a static variable: 第一种方法是使用一些使用静态变量的函数:

Header: 标题:

unsigned int GetNextID();

cpp: CPP:

unsigned int GetNextID()
{
    static unsigned id{0};
    return id++;
}

The other option: 另一种选择:

Header: 标题:

class UniqueIdGenerator
{
public:
    static unsigned int GetNextID();

private:
    static unsigned int mID;
}

cpp: CPP:

unsigned int UniqueIdGenerator::mID = 1;

unsigned int UniqueIdGenerator::GetNextID()
{
    return ++mID;
}

FYI, I've read that the former is not thread safe, but I don't see why the latter would be either. 仅供参考,我读过前者不是线程安全的,但我不明白后者为什么会这样。 If anything, I like the simple function more as it's simpler & shorter. 如果有的话,我更喜欢简单的功能,因为它更简单,更短。

To make it thread-safe you should change to std::atomic<unsigned> mID , and write your function as 要使其成为线程安全的,您应该更改为std::atomic<unsigned> mID ,并将您的函数编写为

return mID.fetch_add(1);

Which version you choose shouldn't matter, although in my opinion the free function would be the one I'd prefer as it's not possible to access the variable outside of the function. 您选择哪个版本无关紧要,但在我看来,自由函数将是我更喜欢的版本,因为它无法访问函数之外的变量。

The difference is scope/visibility of the static variable. 不同之处在于静态变量的范围/可见性。 A class member can be shared by more than one method, the variable in the method cannot. 一个类成员可以由多个方法共享,方法中的变量不能。

On the principle that data should be as private as possible, the static variable in the method is safer if it meets your needs. 根据数据应尽可能私有的原则,如果满足您的需求,方法中的静态变量更安全。

For a discussion of thread safety when initializing the variable, see this question. 有关初始化变量时线程安全性的讨论,请参阅此问题。 , but using the variable is not thread safe unless you take some steps to insure that it is protected (either use and atomic (preferred for a simple value), or protect it with a mutex (if there is more than one piece of data that should be protected)) ,但使用该变量不是线程安全的,除非您采取一些措施来确保它受到保护(使用和原子(首选为简单值),或使用互斥锁保护它(如果有多个数据,应该受到保护))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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