Named Objects in C++
So I have been thinking about how to manage multiple objects without having to store their references/addresses in an array or map (or something even more annoying). What I wanted to do is just create an object (and assign it a name) anywhere in memory and when I need to look it up, I just use its name to find it. But how do I do that: the name of the game is "native c++ events" kaboom.
I have written a short example code below. In it, I create an event inside of some sort of master object, which is defined globally. Your can query a name by raising this event, provoking it to call the handlers in every hooked object. If the object is found, the handler will place its object address in a given pointer:
class GlobalEventClass {
public:
__event void GetObjectByName( __in const char* _cpName, __out void** _pDest );
}Parent;
class Child {
private:
const char* cpObjectName;
public:
~Child()
{
__unhook( &GlobalEventClass::GetObjectByName, Parent, &Child::cpObjectName, this );
}
Child( __in const char* _cpMyName )
: cpObjectName( _cpMyName ) {
__hook( &GlobalEventClass::GetObjectByName, Parent,
&Child::cpObjectName, this );
}
void NameQueryHandler( __in const char* _cpName, __out void** _pDest )
{
if( strstr( cpObjectName, _cpName ) != nullptr )
{
*_pDest = (void*) this;
}
}
};
Child* GetChildByName( __in const char* _cpObjectName )
{
Child* X = nullptr;
__raise Parent.GetObjectByName( _cpObjectName ,(void**) &X);
return X;
}
int main( void ) {
Child Who("Bobby"),Needs("Danny"), *Labels =
new Child("Jamal");
Child* Jamal = GetChildByName("Jamal");
return true;
}
Now I can use any object from anywhere, without having to store its address. I figured this concept would be somewhat useful when you manage different containers, user/client info for example.
The reason why I put this here is because, earlier I was searching Google for hours to find a good implementation for this, hoping there would be a trick to it. Unfortunately without any results, so I had to figure something out by myself (quick! someone pat me on the back!). Well, have fun then...
Thanks.