I have an std::unordered\_map which stores an integer with an object. Here's some code for you to understand:

```
#include <iostream>
#include <unordered_map>
#include <cstdlib>
using namespace std;

class Foo
{
public:
    Foo()
    {
        cout << "Foo created!" << endl;
    }

    ~Foo()
    {

    }
};

typedef std::unordered_map<int, Foo*> FooMap;
FooMap fm;

int allocateID()
{
    cout << "Allocating ID" << endl;
    return rand() % 100;
}

void add()
{
    fm.emplace(allocateID(), new Foo());
}

int main()
{
    srand(time(NULL));

    add();

    return 0;
}

```

Output:

```
Foo created!
Allocating ID

```

The problem here is that the object `Foo` is created **before** an ID is allocated! I tried adding a mutex lock on `allocateID`; it didn't work because `allocateID()` runs **AFTER** the object is created.

How can I modify this program such that `Foo` is created **AFTER** the ID is allocated?

EDIT:

I've played around with the code and used a solution herein to demonstrate:

```
void add(int id, Foo *f)
{
    auto iden = id;
    auto foo = f;
    fm[iden] = foo;
}

void add(Foo *f, int id)
{
    auto iden = id;
    auto foo = f;
    fm[iden] = foo;
}

void add()
{
    int id = allocateID();
    fm[id] = new Foo();
}

```

In the first `add()` function, the output remains the same. This doesn't solve the problem.

In the second `add()` function, the output is different, instead producing:

```
Allocating ID
Foo created!

```

And in the third function, it has been modified with one of the solutions: this function also produces the desired output. The problem with the third function is that it's highly unlikely there would be an empty `add()` function realistically. The only culpable way of solving this issue is to pass the object first **AND THEN** the id. This is probably because the arguments are read from right to left, regardless of the entry requirements because they are created after the arguments are read anyway.