Is this normal behavior for a std::vector?

前端 未结 3 1258
不思量自难忘°
不思量自难忘° 2021-01-16 03:40

I have a std::vector of a class called OGLSHAPE.

each shape has a vector of SHAPECONTOUR struct which has a vector of float and a vector of vector of double. it also

3条回答
  •  轮回少年
    2021-01-16 03:58

    Calling std::vector<>::clear() does not necessarily free all allocated memory (it depends on the implementation of the std::vector<>). This is often done for the purpose of optimization to avoid unnessecary memory allocations.

    In order to really free the memory held by an instance just do:

    template 
    inline void really_free_all_memory(std::vector& to_clear)
    {
        std::vector v;
        v.swap(to_clear);
    }
    
    // ...
    std::vector objs;
    
    // ...
    // really free instance 'objs'
    really_free_all_memory(objs);
    

    which creates a new (empty) instance and swaps it with your vector instance you would like to clear.

提交回复
热议问题