Should I always call vector clear() at the end of the function?

12,103

Solution 1

If we look at the cppreference.com entry for std::vector::~vector it says:

Destructs the container. The destructors of the elements are called and the used storage is deallocated. Note, that if the elements are pointers, the pointed-to objects are not destroyed.

so no you don't have to call clear.

If we want to go to the draft standard, we have to look at section 23.2.1 General container requirements paragraph 4 which says:

In Tables 96 and 97, X denotes a container class containing objects of type T, a and b denote values of type X,[...]

and then look at Table 96 — Container requirements which has the following expression entry:

(&a)->~X()  

and the following note:

note: the destructor is applied to every element of a; all the memory is deallocated.

Update

This is RAII in action and as Bjarne Stroustrup says in Why doesn't C++ provide a "finally" construct?:

Because C++ supports an alternative that is almost always better: The "resource acquisition is initialization" technique (TC++PL3 section 14.4). The basic idea is to represent a resource by a local object, so that the local object's destructor will release the resource. That way, the programmer cannot forget to release the resource.

Solution 2

There is absolutely no need to do that. std::vector and all other containers automatically destroys their elements when they themselves would be destroyed. That means that their destructors are responsible for that action. So, don't.

The beauty of this is that containers are naturally exception safe[1]:

void someFunc(void) {

    std::vector<std::string> contentVector;

    // here are some operations on the vector

    throw std::runtime_error("I just want to throw!");

    contentVector.clear();
}

Will the line contentVector.clear(); be called? No. But you're still safe because it is guaranteed that contentVector's destructor will be called.

From vector[2]:

Destructs the container. The destructors of the elements are called and the used storage is deallocated. Note, that if the elements are pointers, the pointed-to objects are not destroyed.


[1] You still need to make your elements exception safe though (have them properly free their resources whenever their destructors are called).

[2] See comments below for some thoughts on the SGI STL docs.

Solution 3

No need, it will get cleared automatically once it is out of scope i.e destructor will destroy the container object.

Solution 4

You can omit using the .clear() function because vector's destructor runs once contentVector goes out of scope at the '}'.

This deallocates the memory that stores vector's data.

Solution 5

Since I don't think anyone else has mentioned this, but if your vector was

std::vector<std::string*> vector;

you should free the memory allocated to each element before the function finishes (unless you've passed ownership to somewhere else - such as a global variable etc)

for (auto i : vector) {
  delete i;
}
Share:
12,103
Michal Przybylowicz
Author by

Michal Przybylowicz

1) My programming principles: "There is a simple solution for every complex problem but people tend to dig deeper and eventually overwhelm themselves with dirt.", Me So follow these and be clean: KISS DRY YAGNI! 2) About me I like to set my own goals and follow my own path. I am highly motivated person and programming is both my job and a hobby. I like to extend my knowledge in every possible direction and that's why I am not an expert in anything particular... I love programming, playing and writing (simple) computer games, cycling and lifting weights.

Updated on June 14, 2022

Comments

  • Michal Przybylowicz
    Michal Przybylowicz almost 2 years

    I have some simple function that uses vector like this (pseudo code):

    void someFunc(void) {
    
        std::vector<std::string> contentVector;
    
        // here are some operations on the vector
    
        // should I call the clear() here or this could be ommited ?
        contentVector.clear();
    
    }
    

    Should I call the clear() or this could be ommited ?

  • Michal Przybylowicz
    Michal Przybylowicz over 10 years
    Can You provide some link to the STL documentation describing this behavior and just paste it to You answer ?
  • Mark Ransom
    Mark Ransom over 10 years
    SGI is not a definitive reference. Just sayin' since I'm sure it's correct in this case.
  • Mark Garcia
    Mark Garcia over 10 years
    @MarkRansom One links cppreference, another cplusplus.com, me then... ;). The SGI STL website sure is a good, if not definitive, resource. The OP will sure have something to learn from this "classic" site.
  • Mark Ransom
    Mark Ransom over 10 years
    The problem is that SGI does not document the official standard, it documents the precursor to it. There are some subtle and not-so-subtle differences. See stackoverflow.com/questions/5266386/…
  • Mark Garcia
    Mark Garcia over 10 years
    @MarkRansom I know. But it is good to know that it has the same behavior in this case even if it is the precursor to the standard library, which means that you can still rely on the behavior/guarantee for older compilers.
  • MvG
    MvG over 10 years
    These days, with C++11 becoming reasonably common, you probably should be using std::unique_ptr<std::string> instead of std::string* so that the machinery takes care of this as well. And since your foreach loop indicates C++11 being used, that's the way I'd go. By the way, this is one aspect of what this footnote 1 in Mark's answer is talking about.
  • Michael
    Michael over 10 years
    I wrote the auto part because I was too lazy to write out the full version without vim macros. If you have c++11 or boost, then yes. but a pointers destructor does not free the memory (and obviously can't be changed)
  • Shafik Yaghmour
    Shafik Yaghmour over 10 years
  • Shafik Yaghmour
    Shafik Yaghmour over 10 years