<分区>
当 vector 的元素被动态分配/是指针时,我看到的所有问题都是关于管理内存的。我的问题只是关于已在堆栈上分配的 vector ,具有简单类型,例如 int
。
如果我有以下代码:
std::vector<int> vec(5);
for(int i = 0; i < vec.size(); i++) {
std::cout << vec[i] << std::endl;
}
完成后是否需要调用 clear()
?
<分区>
当 vector 的元素被动态分配/是指针时,我看到的所有问题都是关于管理内存的。我的问题只是关于已在堆栈上分配的 vector ,具有简单类型,例如 int
。
如果我有以下代码:
std::vector<int> vec(5);
for(int i = 0; i < vec.size(); i++) {
std::cout << vec[i] << std::endl;
}
完成后是否需要调用 clear()
?
最佳答案
C++ 中的类有一个析构函数,当类对象超出范围或被删除时会调用该析构函数。虽然您认为 std::vector
在后台动态分配空间是正确的,但 std::vector
析构函数将为您释放内存,从而产生一个快乐的无泄漏程序.
来自cppreference page , 当 vector 析构函数被调用时...
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.
另请注意,来自 cppreference清楚了,函数...
Leaves the capacity() of the vector unchanged...
所以当您调用 clear
时,内存实际上并没有被释放! (有关 clear
实际执行的操作的更多信息,请参阅 this SO question)
关于c++ - 完成 vector 后是否需要调用 clear() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49039327/