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?
Aucun commentaire:
Enregistrer un commentaire