选择随机数作为对象 ID?
我正在实现一个引用计数基类,并希望为正在创建的继承该接口的每个对象设置唯一编号。
这是该类的代码片段:
HEADER:
class Object
{
const long long int object_id;
public:
Object();
virtual ~Object();
};
CPP:
Object::Object() : object_id(reinterpret_cast<long long int>(&object_id))
{
}
我很关心这是否安全,如果不是为什么不呢? 我没有使用 rand 和 srand 函数,因为有 2 个原因:
- srand AFAIK 最好在项目中只使用一次,以使随机数尽可能随机。
- 这种方法更精确,因为两个对象不能共享相同的内存位置。
请给我建议。
编辑: 成员object_id是在什么时候创建的?构造函数内部还是外部(初始化列表之前或之后)嗯嗯? 多谢!
I'm implementing a reference counting base class and would like to set uniqe number for each object being created which inherits that interface.
here is a code snippet from that class:
HEADER:
class Object
{
const long long int object_id;
public:
Object();
virtual ~Object();
};
CPP:
Object::Object() : object_id(reinterpret_cast<long long int>(&object_id))
{
}
I'm corious if that's safe approach or not, if not why not?
I didn't use rand and srand function because of 2 reasons:
- srand AFAIK is best to use only one time in a project to make random numbers as much as possible random.
- this approach is more precise since two objects can not share same memory location.
please advice me.
EDIT:
At which point is member object_id created? inside of constructor or outside (before initializatin list or after) hm hm?
thanks alot!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是一个安全的方法。您还没有考虑过非虚拟多重继承。这种情况很少见,但合法。
It's not a safe approach. You haven't considered non-virtual multiple inheritance. It's rare, but legal.
好吧,这是我第一次回答我自己的问题,但这是我为使 unique_id 工作所做的事情。
测试:
这工作得很好,现在每个对象都有它自己的唯一 ID!
OK this is first time I'm answering to my own question but here is what I did to make unique_id work.
TEST:
This works just fine and every object now has it's own unique ID!