【发布时间】:2018-11-25 16:12:52
【问题描述】:
由于使用指针向量的类的构造函数,我有一个ERROR: LeakSanitizer: detected memory leaks。
这里我只是我的代码。
问题.h
class Problem {
protected:
std::vector<const Object*> pointer_vector;
public:
// Constructor
Problem();
};
Problem.cc
Problem::Problem() {
this->pointer_vector.push_back(new Object(parameter_list_1));
this->pointer_vector.push_back(new Object(parameter_list_2));
// here I just want to push back the pointer into the vector
}
因为我的代码仍然有效。但正如我提到的,我得到了ERROR: LeakSanitizer: detected memory leaks。
我认为我在 push_back 上做错了,我正在询问正确的方法。
问题是我想问一些通用的方法来解决这个问题。喜欢
如何使用raw pointer 改进此代码。
因为我认为我们肯定有很好的方法来解决这个问题,并且没有找到可能的重复项。如果您需要详细的错误报告,我会添加它们。
谢谢!
【问题讨论】:
-
显示minimal reproducible example。您显示的代码中没有双重释放。问题出在您未显示的代码中。
-
std::vector<Object>对你来说可能已经足够了。否则std::vector<std::unique_ptr<const Object>>. -
好的。我删除了这里不相关的东西。感谢您的建议。
标签: c++ pointers memory-leaks