2
votes

I have the following vector:

  • vector<boost::shared_ptr<Entity>> entities;

In order to reset the vector I am using erase

  • entities.erase(entities.begin(), entities.end());

Question

is this procedure correct? Will it lead to memory leak? should I also delete FactClass?


Class Entity

The constructor of class Entity takes as argument a vector of shared pointers of type FactClass

class Entity
{
public:
    Entity(std::vector<boost::shared_ptr<FactClass>>);
    vector<boost::shared_ptr<FactClass>> getClassFact() const;
private:
    vector<boost::shared_ptr<FactClass>> _listFacts;
};

Class FactClass

The constructor of class FactClass takes as argument a vector of shared pointers of type Fact etc.

class FactClass
{
    public:
        FactClass(std::vector<boost::shared_ptr<Fact>>);
        std::vector<boost::shared_ptr<Fact>> getFacts() const;
    private:
        vector<boost::shared_ptr<Fact>> _fact;
};

3
I actually Wanted to reset the vector that's why I used erase. what is the difference if I use clear? - Hani Goc
clear is correct too (and more explicit about intention). - Jarod42
@HaniGoc it's less typing, less errorprone and it's more expressive of intent - sehe
"should I also delete FactClass?" If you still needed to do that, what purpose do you think shared_ptr would serve? Why would you bother to use it if it didn't do that for you? - Jonathan Wakely

3 Answers

2
votes

No, this will not leak memory (if the implementation of the shared_ptr is correct, which it is for boost's and std's shared_ptr). The moment the shared_ptr object is destroyed the memory will be released.

1
votes

clear() is defined in terms of erase(), which has linear complexity. In erase we provide range as parameters while clear is the erase implementation of the whole range.

  • entities.erase(entities.begin(), entities.end());

is same as

  • entities.clear();

And they leave the capacity() of the vector unchanged, so no memory leak.

0
votes

Your code will not leak, thanks to having smart pointers (shared_ptr) in the vector.

You should pay attention when having owning raw pointers, but when you have smart pointers, the destructor of the smart pointer will do proper cleanup.

(For the specific case of shared_ptr, there is a reference count associated to the pointers; so, the destructor will decrease the ref count of the associated smart pointer, and as soon as the ref count reaches zero, meaning that there is no more reference to the pointed object, this is automatically deleted.)

Anyway, I prefer calling the vector::clear() method, which is more explicit about your intent of "resetting" the vector.