c++ - 完成 vector 后是否需要调用 clear() ?

标签 c++ memory-management

<分区>

当 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/

相关文章:

c++ - 无符号长整型和位移位

c++ - 如何在小型转储中更改模块的校验和?

c++ - 为什么编译器在编译时不知道局部变量的地址?

c++ - delete[] 如何知道数组的大小?

c++ - 创建 OpenGL 2D View 相机,但使用模型 View 投影相机

c++ - 打印 Log4CXX 异常堆栈跟踪

ios - 如何在应用程序中存储多个图像对象而不收到内存警告

iOS 自定义键盘扩展 - 内存限制

java - Java 中 Thread 中的 WeakReference

c - 解决 munmap 警告消息