我在sourceFile.cpp
. functionA()
首先调用并插入 key1、key2 和 key3 的条目。然后functionB()
被调用以使用 3 个键的向量。我想在退出后释放所有内存functionC()
。在将条目放入 3 个键的映射中的三种方法中,哪种方法正确/更好?
Class ClassA { ... }
ClassA *key1 = new ClassA();
ClassA *key2 = new ClassA();
ClassA *key3 = new ClassA();
static map<ClassA*, vector<pair<char*, char*> > > stringMap;
// 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?
vector<pair<char*, char*> > v3;
stringMap[key3] = v3; //
}
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 ???
// what about the vector for key3?
}