简体   繁体   中英

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!

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. 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 delete d there as well.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM