我想map在类的构造函数中初始化一个(指向a的指针)。我编写的程序可以编译,但由于分段错误而在运行时失败。我可以通过动态分配内存来解决问题,map但Valgrind会通知我内存泄漏。如何正确初始化类?
这是一个例子
#include <iostream>
#include <map>
#include <string>
#include <vector>
class MemoryLeak {
public:
MemoryLeak(std::vector<std::string>& inp) {
int i = 0;
std::map<std::string, int>* tmp = new std::map<std::string, int>;
for (std::string& s : inp) {
//(*problem_map)[s] = i++; // Line 12: causes a seg fault
(*tmp)[s] = i++;
}
problem_map = tmp; // Line 15: memory leak
}
std::map<std::string, int>* problem_map;
};
int main() {
std::vector<std::string> input{"a", "b"};
MemoryLeak mem = MemoryLeak(input);
for (auto const& it : *(mem.problem_map)) {
std::cout << it.first << ": " << it.second << "\n";
}
return 0;
}
当我取消注释line 12(并注释掉Line 15)时,程序编译但似乎发生了内存泄漏。有人可以告诉我我做错了什么吗?一个更合适的构造函数会是什么样子?