Where does a std::vector allocate its memory?

后端 未结 4 1970
生来不讨喜
生来不讨喜 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:44

    Does a std::vector allocate memory for its elements on the heap?

    Yes. Or more accurately it allocates based on the allocator you pass in at construction. You didn't specify one, so you get the default allocator. By default, this will be the heap.

    But how does it free that heap memory?

    Through its destructor when it goes out of scope. (Note that a pointer to a vector going out of scope won't trigger the destructor). But if you had passed by value to sub you'd construct (and later destruct) a new copy. 5 would then get pushed back onto that copy, the copy would be cleaned up, and the vector in main would be untouched.

提交回复
热议问题