Jigao
Jigao

Reputation: 15

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.

Here I simply my code.


Problem.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
}

Since my code still works. But I got the ERROR: LeakSanitizer: detected memory leaks as I mentioned.

I think I did something wrong with the push_back and I am asking about the proper way to do that.
The thing is I want to ask some general way to solve that. Like
How can I improve this code using the 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!

Upvotes: 0

Views: 104

Answers (2)

super
super

Reputation: 12968

Every object that you create with new will have to be deleteed at some point. 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() {
    for (auto ptr : pointer_vector)
        delete ptr;
}

If you ever remove objects from the vector, you have to make sure that they are deleted there as well.

Please Note: the proper way to do this is however to use smart pointers as Matthieu already said in his answer.

Upvotes: 3

Matthieu Brucher
Matthieu Brucher

Reputation: 22023

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;

Upvotes: 6

Related Questions