I have the following code in sourceFile.cpp. functionA() is first called and inserted entires for key1, key2 and key3. Then functionB() gets called to use the vectors for the 3 keys. I want to free all memory after exiting functionC(). Among the three ways to put an entry into the map for the 3 keys, which is correct / better?
Class ClassA { ... }
ClassA *key1 = new ClassA();
ClassA *key2 = new ClassA();
ClassA *key3 = new ClassA();
// which way of adding an entry into StringMap is better? key1, key2 or key3
void functionA() {
// insert entries into stringMap for key1 and key2
vector<pair<char*, char*> > *v1 = new vector<pair<char*, char*> >();
stringMap[key1] = *v1;
stringMap[key2]; // map will insert one vector<pair<char*, char*> > object
// is this vector object on heap or stack?
void functionB() {
// get entries for key1, key2 and key3
// use vector.push_back() to populate vectors
}
void functionC() {
// so when program exits this function, all memory is released
vector<pair<char*, char*> > *v1 = stringMap[key1];
v1->clear(); // or loop and v1->erase()
stringMap.erase(key1);
delete v1;
vector<pair<char*, char*> > v2 = stringMap[key2];
v2.clear();
stringMap.erase(key2);
// v2 was inserted by map, does it need to delete v2 ???
Thanks, Cubbi. You provided a very nice solution. I'd like to give more information for the question. ClassA is in shared library which I cannot change it at all. My current implementation uses a pointer to ClassA to pass around and invoke functionB and C. Do you think I can write a struct to wrap ClassA in shared library? Also I don't think I can pass any int value for comparison. Also, in a multi-threading environment, the map and vector may not be thread safe.