在类构造函数中初始化映射时,如何避免内存泄漏
How can I avoid a memory leak when initializing a map in the constructor of a class?
我想在类的构造函数中初始化(指向A(map
的指针。我编写编译的程序,但由于细分故障而在运行时失败。我可以通过动态的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
(时,该程序会编译,但似乎发生了内存泄漏。有人可以告诉我我在做什么错吗?更合适的构造函数将如何?
segfault :
您的指针problem_map
在第12行中未经启发。这就是为什么segfault。您不需要tmp
您只能执行此操作:
problem_map = new std::map<std::string, int>;
for (std::string& s : inp) {
(*problem_map)[s] = i++;
}
现在泄漏,您有两个选择:
1(添加一个驱动器,一个复制构建器和复制分配操作员(或使其删除(。请参阅三个规则
class MemoryLeak {
public:
~MemoryLeak() {
delete problem_map;
}
MemoryLeak(const MemoryLeak& ) = delete;
MemoryLeak& operator=(const MemoryLeak& ) = delete;
MemoryLeak(std::vector<std::string>& inp) {
int i = 0;
problem_map = new std::map<std::string, int>;
for (std::string& s : inp) {
(*problem_map)[s] = i++;
}
}
std::map<std::string, int>* problem_map;
};
2(不要存储指针,而是地图
class MemoryLeak {
public:
MemoryLeak(std::vector<std::string>& inp) {
int i = 0;
for (std::string& s : inp) {
problem_map[s] = i++;
}
}
std::map<std::string, int> problem_map;
};
相关文章:
- 删除指针内存分配以避免内存泄漏
- 如何使用抽象类指针避免内存泄漏
- 在类构造函数中初始化映射时,如何避免内存泄漏
- 避免C++内存泄漏?
- 在使用Embind的Javascript中,仅仅调用deleteLater()就足以避免内存泄漏吗
- 提升::ASIO 受体避免内存泄漏
- 如何避免内存泄漏,使用带有STL容器的C++
- 重新分配内存以避免内存碎片
- 如何避免内存泄漏与返回常量字符*
- C++:使用指针存储/访问大型对象以避免内存不足
- 如何在设计实现级别避免内存泄漏
- 如何避免C++内存泄漏
- C++ 移动构造函数和常量成员指针或常量成员,如何对它们进行 NULIZE 以避免内存泄漏
- 在这种情况下,我是否需要清空映射的内容以避免内存泄漏
- 引发异常时避免内存泄漏的方法
- 如何正确释放ID3D11ShaderResourceView**以避免内存泄漏
- 我必须使用delete来避免内存泄漏吗?我使用new来分配结构实例
- 从二叉树中删除节点以避免内存泄漏
- 用异常避免内存泄漏
- 如何构建JNI调用以避免内存泄漏