Purpose of GUIDs in COM
What is the purpose of GU开发者_运维知识库IDs in COM?
Is it only to avoid name conflicts?
It serves the exact same purpose as a name. A COM client can ask the system to create a COM object using a simple identifier (CoCreateInstance). That identifier has the scope of the full machine. Different chunks of code written by programmers that don't know each other and work for different companies live at that scope.
The problem with names is that people suck at picking good names. The odds that one programmer picks the exact same name as another programmer, 3000 miles away and 5 years ago are high. Names like "Record", "Database" etc would be popular choices. Evident at this website too, lot's of users named "Jason" or "Mike". They don't mind, they know their own name when they review their profile. Context. Impossible for me to find them back though when they send me an email with just their user name, following up on a question with a generic subject string.
Getting a name collision and COM creating the wrong object is disastrous. The program stops working because it is getting a completely wrong object. Finding out why is difficult, the error message sucks. Actually fixing the problem is impossible. Calling programmer B and ask him in the friendliest possible way to "pick a different name, somebody already picked yours" doesn't work. Automatic response is "call programmer A instead".
This is not a problem when you use a GUID instead of a name. They are Globally Unique IDs. The odds of getting a collision are astronomically small.
Probably, as it would guarantee a globally unique identifier for each object.
As the name suggests, it's an identifier and serves the same purpose as any other identifier. As you mentioned, avoiding name conflicts is one use. Another advantage is that it is only 128 bits long (as compared to a name which could be arbitrarily long) so comparing two GUIDs is much faster than comparing their corresponding names.
As it name suggests, GUID is a globally unique identifier. Which means that if one developer generates two GUIDs he gets two different GUIDs and if two developers who don't even know about each other generate one GUID each - either at the same moment or at different moments - they again get two different GUIDs.
Now consider a problem - any developer needs an ability to introduce new interfaces and classes and make them uniquely identifiable. That's because if you get an interface pointer and your program treats it as some InterfaceA*
but it really is not an InterfaceA*
you've got a major problem - your program runs into undefined behavior - crashes or produces unexpected results.
The above problem is easily solved with GUIDs. Every developer creates a new (and thus unique) GUID value for every new interface or class he introduces. This is reliable and convenient (except that GUIDs are not that human-readable).
精彩评论