使用整数指针作为唯一ID是多么糟糕? C ++ 11 [英] How bad is to use integer pointers as unique ids? C++11
问题描述
我有一个类,当实例化需要获得几个唯一的id工作。
最初我想使用一个静态函数来分配和增量。
我不需要它们是连续的,只是唯一的。
I got a class that when instantiated needs to obtain a few unique ids to work. Initially I thought using an static function that assigns and increments. I don't need them to be consecutive, only unique.
class A {
int id_1;
int id_2;
int id_3;
public:
static int last_id=0;
static int get_id(){ return A::last_id++; }
...
A(){ id_1 = A::get_id(); id_2 = A::get_id(); id_3 = A::get_id(); }
};
现在,我想进行多线程。
我认为静态函数将是一个瓶颈,因为我在开始构建这些对象的几十万个实例。
我不会销毁任何实例,直到程序结束,所以在初始化之后,它们是固定的。
无论如何,它们不是在编译时计算的,因为数量取决于命令行参数。
Now, I' thinking in going multithreading. I think the static function will be a bottleneck, since I'm constructing a few hundred thousand instances of these objects at the start. I don't destroy any instance until the end of the program, so after initialization they are fixed. Anyway they are not computed at compile time because the quantity depends of command-line arguments.
我想到的另一种方法是使用内存地址,
An alternative I was thinking of was using memory addresses, they are unique in a single computer at least.
如下:
class A {
int* id_1;
int* id_2;
int* id_3;
public:
static int last_id=0;
static int get_id(){ return A::last_id++; }
...
A(){ id_1 = new int(0); id_2 = new int(0); id_3 = new int(0); }
~A() { delete id_1; delete id_2; delete id_3(); }
};
然后我将读取标识符作为指针的地址。
Then I would read the identifiers as the address of the pointers.
问题:使用这样的指针是否有意义?
Question: Does this make any sense to use pointers like this?
推荐答案
远离你原来的解决方案。 不要过早优化!增加 int
非常便宜!我唯一的建议是使用 std :: atomic< int>
而不是 int
。
You're really not that far off with your original solution. Don't prematurely optimize! Incrementing an int
is very cheap! My only suggestion would be to use std::atomic<int>
instead of int
.
class A {
int id_1;
int id_2;
int id_3;
static int get_id() {
static std::atomic<int> next_id(1);
return ++next_id;
}
public:
A() :
id_1(get_id()),
id_2(get_id()),
id_3(get_id())
{ }
// deal with copying by disabling
A(const A&) = delete;
A& operator=(const A&) = delete;
// move is okay
A(A&&) noexcept = default;
A& operator=(A&&) noexcept = default;
};
假设您创建的不超过 2 ^ 31 / code>实例
A
,您不必担心溢出。
Assuming you don't create more than 2^31/3
instances of A
, you don't have to worry about overflow.
这篇关于使用整数指针作为唯一ID是多么糟糕? C ++ 11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!