静态变量的地址 [英] Address of a static variable
问题描述
我想做一个简单的类来唯一的ID转换。我正在考虑添加一个静态方法:
I am trying to do a simple class to unique ID conversion. I am thinking about adding a static method:
class A {
static int const *GetId() {
static int const id;
return &id;
}
};
每个类将由唯一的 int const *
。这是保证工作吗?返回的指针真的是唯一的吗?有没有更好的更简单的解决方案?
Each class would then be identified by unique int const *
. Is this guaranteed to work? Will the returned pointer really be unique? Is there any better simpler solution?
我也想过指向 std :: type_info
:
class A {
static std::type_info const *GetId() {
return &typeid(A);
}
};
这更好吗?
修改:
我不需要使用ID进行序列化。我只想识别一小组基类,我想要一些类的所有子类具有相同的id
I don't need to use the id for serialization. I only want to identify a small set of base classes and I want all subclasses of some class to have the same id
推荐答案
As我注意到至少MSVC 2008或2010优化静态变量,以便下面的 GetId
函数返回相同的地址,即使对于不同的类。
As I have noticed at least MSVC 2008 or 2010 optimizes the static variable, so that the following GetId
function returns same address even for different classes.
static int const *GetId() {
static const int i = 0;
return &i;
}
因此,未初始化的常量静态变量的地址可能不能用于识别。最简单的解决方法是删除 const
:
Therefore address of uninitialized constant static variable may not be used for identification. The simplest fix is to just remove const
:
static int *GetId() {
static int i;
return &i;
}
另一个生成ID的解决方案似乎有效,函数作为计数器:
Another solution to generate IDs, that seems to work, is to use a global function as a counter:
int Counter() {
static int i = 0;
return i++;
}
然后在要识别的类中定义以下方法:
And then define the following method in the classes to be identified:
static int GetId() {
static const int i = Counter();
return i;
}
由于要定义的方法总是相同的,基类:
As the method to be defined is always the same, it may be put to a base class:
template<typename Derived>
struct Identified {
static int GetId() {
static const int i = Counter();
return i;
}
};
然后使用奇怪的重复模式:
And then use a curiously recurring pattern:
class A: public Identified<A> {
// ...
};
这篇关于静态变量的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!