Search code examples
c++loopsscopeobject-lifetime

Creating unknown number of objects with each having specific object name at runtime c++


I want to create an unknown number of objects each with a specific object name inside the main-method at runtime. The objects should be existent until the program ends (main-method ends). Note, that in my case the objects are Fields.

I thought about a solution like this:

for ( i=1 ; i <= NumberOfObjects ; i++)
{

if (i==1)
{
MyClass *ObjectName1 = new MyClass();

}

if (i==2)
{
MyClass *ObjectName2 = new MyClass();

}

.   //more if statements for more objects
.
.

} //for loop closed

Questions:

  1. I don't think this solution is good, since the number of created objects still would be limited to the if-statements within the for-loop. Any better solutions?

  2. Scope of pointers in loops: When the if-blocks are exited the pointers are out of scope. How can I access the with "new" created objects afterwards?


Solution

  • Named variables are removed once the code is compiled and doesn't mean anything to you afterwards.

    Looks like you need a look up table, use an std::map or std::unordered_map with string key as the name of the object.

    std::map<std::string, MyClass*> variablesTable;
    for ( i=1 ; i <= NumberOfObjects ; i++)
    {
        std::ostringstream oss << "name" << i;
        variablesTable[oss.str()] = new MyClass();    //you actually need to check if it exists, otherwise will be overwritten.
    }    
    

    As if you want each created to run a separate code for each object, you can have a table of function objects (or just store both in a tuple) like this std::map<std::string, std::<MyClass, Func>>.

    If you want to lookup just use,

    MyClass* object = variablesTable[strName];
    object->CallFunction();
    

    P.S. A known trick for hash_maps is to run script before building the project to convert any literal string to int, because comparing int is faster than strings. At least I know this was used in the Uncharted series (but hardly relevant to your case).