对于某些对象的唯一 id,我可以通过两种方式创建一个计数器,但我不知道哪种更好,因为它们在代码上有很大不同(尽管可能不是字节码,我不知道)。
第一种方法是使用一些使用静态变量的函数:
标题:
unsigned int GetNextID();
cpp:
unsigned int GetNextID()
{
static unsigned id{0};
return id++;
}
另一种选择:
标题:
class UniqueIdGenerator
{
public:
static unsigned int GetNextID();
private:
static unsigned int mID;
}
cpp:
unsigned int UniqueIdGenerator::mID = 1;
unsigned int UniqueIdGenerator::GetNextID()
{
return ++mID;
}
仅供引用,我有 read前者不是线程安全的,但我不明白为什么后者也是。如果有的话,我更喜欢 simple 函数,因为它更简单、更短。
最佳答案
要使其成为线程安全的,您应该更改为 std::atomic<unsigned> mID
, 并将你的函数写成
return mID.fetch_add(1);
您选择哪个版本无关紧要,但在我看来,自由函数是我更喜欢的版本,因为它无法访问函数外部的变量。
关于c++ - 函数内部的静态变量与C++中的静态类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37032606/