【发布时间】:2016-08-30 04:18:18
【问题描述】:
对于某些对象的唯一 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 认为前者不是线程安全的,但我不明白为什么后者也是。如果有的话,我更喜欢简单的功能,因为它更简单、更短。
【问题讨论】:
-
FWIW,你是对的。两种实现都不是线程安全的。
-
只是为了让它更清楚,因为出于某种原因人们关注线程安全(如果我的问题含糊不清,我很抱歉):我在问为什么任何一种方法都会更好。如果它们只是线程不安全,那么线程安全不应该进入讨论。
标签: c++ static static-variables translation-unit