C++ 最佳实践:如何获取对象的唯一标识符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14585385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:28:42  来源:igfitidea点击:

Best Practice : How to get a unique identifier for the object

c++

提问by deimus

I've got several objects and need to generate a unique identifier for them which will not be changed/repeated during the lifetime of each object.

我有几个对象,需要为它们生成一个唯一标识符,在每个对象的生命周期内不会更改/重复。

Basically I want to get/generate a unique id for my objects, smth like this

基本上我想为我的对象获取/生成一个唯一的 id,就像这样

int id = reinterpret_cast<int>(&obj);

or

或者

int id = (int)&obj;

I understand the codes above are bad ideas, as int might not be large enough to store the address etc.

我知道上面的代码是坏主意,因为 int 可能不够大,无法存储地址等。

So whats the best practice to get a unique identifier from the object, which will be a portable solution ?

那么从对象中获取唯一标识符的最佳实践是什么,这将是一个可移植的解决方案?

回答by dhavenith

Depending on your "uniqueness"-requirements, there are several options:

根据您的“唯一性”要求,有多种选择:

  • If unique within one address space ("within one program execution") is OK and your objects stay where they are in memorythen pointers are fine. There are pitfalls however: If your objects live in containers, every reallocation may change your objects' identity and if you allow copying of your objects, then objects returned from some function may have been created at the same address.
  • If you need a more global uniqueness, for instance because you are dealing with communicating programs or data that is persistent, use GUIDs/UUIds, such as boost.uuid.
  • You could create unique integers from some static counter, but beware of the pitfalls:
    • Make sure your increments are atomic
    • Protect against copying or create your custom copy constructors, assignment statements.
  • 如果在一个地址空间内唯一(“在一个程序执行内”)是可以的,并且您的对象保持它们在内存中的位置,那么指针就可以了。然而,也有一些陷阱:如果你的对象存在于容器中,每次重新分配都可能改变你的对象的身份,如果你允许复制你的对象,那么从某个函数返回的对象可能已经在相同的地址创建。
  • 如果您需要更全局的唯一性,例如因为您正在处理持久性通信程序或数据,请使用 GUID/UUId,例如boost.uuid
  • 您可以从一些静态计数器创建唯一的整数,但要注意陷阱:
    • 确保你的增量是原子的
    • 防止复制或创建自定义复制构造函数、赋值语句。

Personally, my choice has been UUIDs whenever I can afford them, because they provide me some ease of mind, not having to think about all the pitfalls.

就我个人而言,只要我负担得起,我就会选择 UUID,因为它们让我安心,而不必考虑所有的陷阱。

回答by Luchian Grigore

If the objects need to be uniquely identified, you can generate the unique id in the constructor:

如果需要唯一标识对象,可以在构造函数中生成唯一id:

struct Obj
{ 
   int _id;
   Obj() { static int id = 0; _id = id++; }
};

You'll have to decide how you want to handle copies/assignments (same id - the above will work / different id's - you'll need a copy constructor and probably a staticclass member instead of the staticlocal variable).

您必须决定如何处理副本/分配(相同的 id - 以上将起作用 / 不同的 id - 您需要一个复制构造函数,并且可能需要一个static类成员而不是static局部变量)。

回答by hcc23

When I looked into this issue, I fairly quickly ended up at the Boost UUIDlibrary (universally unique identifier, http://www.boost.org/doc/libs/1_52_0/libs/uuid/). However, as my project grew, I switched over to Qt's GUIDlibrary (globally unique identifier, http://doc.qt.digia.com/qt/quuid.html).

当我研究这个问题时,我很快就找到了Boost UUID库(通用唯一标识符,http://www.boost.org/doc/libs/1_52_0/libs/uuid/)。然而,随着我的项目的增长,我切换到Qt 的 GUID库(全局唯一标识符,http://doc.qt.digia.com/qt/quid.html)。

A lesson learned for me though was to start declaring your own UUID class and hide the implementation so that you can switch to whatever you find suitable later on.

不过我学到的一个教训是开始声明你自己的 UUID 类并隐藏实现,这样你就可以稍后切换到你觉得合适的任何东西。

I hope that helps.

我希望这有帮助。

回答by Audrius Meskauskas

It does not look like a bad idea to use the object address as the unique (for this run) identifier, directly. Why to cast it into integer? Just compare pointers with ==:

直接使用对象地址作为唯一(对于此运行)标识符看起来并不是一个坏主意。为什么要把它转换成整数?只需将指针与==

MyObject *obj1, *obj2;
...
if (obj1 == obj2) ...

This will not work, of course, if you need to write IDs to database or the like. Same values for pointers are possible between runs. Also, do not overload comparison operator (==).

当然,如果您需要将 ID 写入数据库等,这将不起作用。两次运行之间可以使用相同的指针值。另外,不要重载比较运算符 ( ==)。

回答by Sergei Nikulov

If you need unique id for distributed environment use boost::uuid

如果您需要分布式环境的唯一 ID,请使用boost::uuid

回答by Crog

If your object is a class then you could have a static member variable which you intestinal to 0. Then in the constructor you store this value into the class instance and increment the static variable:

如果您的对象是一个类,那么您可以有一个静态成员变量,您将其设置为 0。然后在构造函数中,您将此值存储到类实例中并增加静态变量:

class

班级

Indexed
{
public:
   Indexed() :
       m_myIndex( m_nextIndex++ )
   { }

   int getIndex() const
   { return m_myIndex; }

private:
   const int m_myIndex;
   static int m_nextIndex;
};