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

后端 未结 5 695
灰色年华
灰色年华 2020-12-08 14:34

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

void someFunc(void) {

    std::vector contentVector;

    // here a         


        
5条回答
  •  执念已碎
    2020-12-08 14:39

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

提交回复
热议问题