[英]Proper way to push_back pointer to a vector
I have a ERROR: LeakSanitizer: detected memory leaks
due to a constructor of a class using a vector of pointers. 我有一个ERROR: LeakSanitizer: detected memory leaks
由于使用指针向量的类的构造函数而导致的ERROR: LeakSanitizer: detected memory leaks
。
Here I simply my code. 在这里,我只是我的代码。
Problem.h 问题h
class Problem {
protected:
std::vector<const Object*> pointer_vector;
public:
// Constructor
Problem();
};
Problem.cc 问题.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
}
Since my code still works. 由于我的代码仍然有效。 But I got the ERROR: LeakSanitizer: detected memory leaks
as I mentioned. 但是我收到了ERROR: LeakSanitizer: detected memory leaks
如上所述, ERROR: LeakSanitizer: detected memory leaks
。
I think I did something wrong with the push_back
and I am asking about the proper way to do that. 我想我在push_back
做错了,我在问这样做的正确方法。
The thing is I want to ask some general way to solve that. 问题是我想问一些一般的方法来解决这个问题。 Like 喜欢
How can I improve this code using the raw pointer
. 如何使用raw pointer
改进此代码。
Because I think we have certainly beautiful way to solve that and not found possible duplicates. 因为我认为我们肯定有解决此问题的绝妙方法,但没有发现可能的重复项。 If you need detailed error reporting, I will add them. 如果您需要详细的错误报告,我将添加它们。
Thanks! 谢谢!
Don't overthink this. 不要想太多。
It seems that everything you have in your object gets allocated there, so use smart pointers: 您对象中拥有的所有内容似乎都在那里分配了,因此请使用智能指针:
std::vector<std::unique_ptr<Object>> pointer_vector;
Every object that you create with new
will have to be delete
ed at some point. 您用new
创建的每个对象都必须在某个时候delete
。 It's your responsibility to do that. 这样做是您的责任。 In your case the easiest solution is to add it in the destructor for your Problem
class. 在您的情况下,最简单的解决方案是将其添加到Problem
类的析构函数中。
Problem::~Problem() {
for (auto ptr : pointer_vector)
delete ptr;
}
If you ever remove objects from the vector, you have to make sure that they are delete
d there as well. 如果从矢量中删除了对象,则必须确保也将其delete
。
Please Note: the proper way to do this is however to use smart pointers as Matthieu already said in his answer. 请注意:正确的方法是使用智能指针,正如Matthieu在其答案中已经说过的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.