Where does a std::vector allocate its memory?

后端 未结 4 1976
生来不讨喜
生来不讨喜 2020-12-13 13:53

Consider the following code snippet:

#include 
using namespace std;

void sub(vector& vec) {
    vec.push_back(5);
}

int main()         


        
4条回答
  •  鱼传尺愫
    2020-12-13 14:32

    Also note that your vector (vec) is object itself. It resides on the stack and when this object goes out of scope (which is end of main in your case), it is destructed. Memory for elements is allocated during initialization of this object and released with its destruction, which is a lovely example of RAII idiom, since the resource management of elements is tied to the lifespan of vector object.

提交回复
热议问题