In a system where registered objects must have unique names, I want to use/include the object\'s this pointer in the name. I want the simplest way to create
In a system where registered objects must have unique names, I want to use/include the object's this pointer in the name.
An object's address is not necessarily unique. Example: You dynamically allocate such an object, use it for a while, delete it, and then allocate another such object. That newly allocated object might well have the same the object address as the previous.
There are far better ways to generate a unique name for something. A gensym counter, for example:
// Base class for objects with a unique, autogenerated name.
class Named {
public:
Named() : unique_id(gensym()) {}
Named(const std::string & prefix) : unique_id(gensym(prefix)) {}
const std::string & get_unique_id () { return unique_id; }
private:
static std::string gensym (const std::string & prefix = "gensym");
const std::string unique_id;
};
inline std::string Named::gensym (const std::string & prefix) {
static std::map counter_map;
int & entry = counter_map[prefix];
std::stringstream sstream;
sstream << prefix << std::setfill('0') << std::setw(7) << ++entry;
return sstream.str();
}
// Derived classes can have their own prefix. For example,
class DerivedNamed : public Named {
public:
DerivedNamed() : Named("Derived") {}
};