This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.


  Automatic Object ID Generation
  Submitted by

Here's a little technique that I've found pretty useful but haven't seen anywhere other than my code :). It is pretty often that there is a number of logically grouped objects in a program that need to contain a name and a unique ID for hashing or some other lookup method. For instance, you might have lights named, say, Light01, etc, cameras named Camera01, etc, static geometry named Level01Room01 or whatever, and objects named, say, EvilDemonBoss or Bob. There are many techniques for generating unique ID's, but there's no simple way to generate an ID that is absolutely guaranteed to be unique without checking the rest of the ID's.

The proposed technique takes care of that problem in a pretty simple and straightforward way, although it requires that ID's can not be changed once set, and that every object has a name. Here's the basic outline of the technique using C strings, although STL strings or a custom string class could be used as long as it's a dynamic instance (static instances won't generate unique IDs for obvious reasons)

class Base

virtual char *GetName() { return strdup(m_strName); } virtual void SetName(char *p) { m_strName = strdup(p); } virtual long GetID() { return m_nID; }

protected: union { char *m_strName; long m_nID; }; };

What happens is pretty obvious: whenever a name is allocated, its pointer is used as the ID. Pointers are unique, therefore ID's are unique. Changing the name of an object changes its ID. The reason GetName() and SetName() use strdup() is that otherwise objects may end up hashed under the same ID as a result of something like


Not an easy bug to track, so I just play it safe and don't allow direct pointer access.


The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.


Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.