Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shall I clear a vector of unique_ptr in destructor in c++11 even if valgrind doesn't show memory leak

Giving the Holder class below:

    class Holder {
        string  name;
        std::vector<std::unique_ptr<Object>> objects;
    public:
        Holder(string name): name(name){
        }   

        ~Holder(){};
        Holder & operator=(const Holder & holder) = delete;  

    vector<unique_ptr<Object>> const& Holder::getContent()const{
        return this->objects;
    }

    void Holder::add(unique_ptr<Object> objPtr){
       this->objects.push_back(move(objPtr));
    }


    };

If I am calling my Holder object in the method below:

void HolderTest::addObject(){
    Holder *holder = new Holder("bag");
    holder->add(unique_ptr<Object>(new Object("test")));
    vector<unique_ptr<Object>> const& objects = holder->getContent();
    const std::string name = objects[0].get()->name();
    CPPUNIT_ASSERT_EQUAL((string)"test", name);
    delete holder;
}

My question is: should I call my vector of unique_ptr's clear method in the Holder destructor to avoid memory leak like below?

~Holder(){
  this->objects.clear();
};

My other question can I still use "Valgrind Tools Integration" version 3.0.0.201502180018 for finding memory leaks in a c++11 application or it is not able to find memory leak in c++11 programs?

like image 405
Govan Avatar asked Oct 18 '25 00:10

Govan


1 Answers

You do not have to call clear manually. The destructor of std::vector<T> will call destructors of std::unique_ptr<T> automatically.

The major advantage of smart pointers over built-in pointers is that you don't have to deal with manual clean-up.

like image 92
Sergey Kalinichenko Avatar answered Oct 20 '25 15:10

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!