Should I always call vector clear() at the end of the function?(我应该总是在函数末尾调用 vector clear() 吗?)
问题描述
我有一些使用像这样的向量的简单函数(伪代码):
I have some simple function that uses vector like this (pseudo code):
void someFunc(void) {
std::vector<std::string> contentVector;
// here are some operations on the vector
// should I call the clear() here or this could be ommited ?
contentVector.clear();
}
我应该调用 clear() 还是可以省略?
Should I call the clear() or this could be ommited ?
推荐答案
如果我们看看 cppreference.com std::vector::~vector 的条目说:
If we look at the cppreference.com entry for std::vector::~vector it says:
破坏容器.调用元素的析构函数并释放已使用的存储空间.请注意,如果元素是指针,则指向的对象不会被销毁.
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.
所以不,您不必调用clear.
如果我们要查看草案标准,我们要看看23.2.1
一般容器要求4段,它说:
If we want to go to the draft standard, we have to look at section 23.2.1
General container requirements paragraph 4 which says:
在表 96 和 97 中,X 表示包含 T 类型对象的容器类,a 和 b 表示 X 类型的值,[...]
In Tables 96 and 97, X denotes a container class containing objects of type T, a and b denote values of type X,[...]
然后查看具有以下表达式条目的表 96 — 容器要求
:
and then look at Table 96 — Container requirements
which has the following expression entry:
(&a)->~X()
以及以下注意事项:
注意:析构函数应用于a的每个元素;所有内存都被释放.
note: the destructor is applied to every element of a; all the memory is deallocated.
更新
这是 RAII 的实际操作,正如 Bjarne Stroustrup 在为什么 C++ 不提供finally"构造?:
This is RAII in action and as Bjarne Stroustrup says in Why doesn't C++ provide a "finally" construct?:
因为 C++ 支持一种几乎总是更好的替代方法:资源获取即初始化"技术(TC++PL3 第 14.4 节).基本思想是用一个本地对象来表示一个资源,这样本地对象的析构函数就会释放该资源.这样程序员就不会忘记释放资源了.
Because C++ supports an alternative that is almost always better: The "resource acquisition is initialization" technique (TC++PL3 section 14.4). The basic idea is to represent a resource by a local object, so that the local object's destructor will release the resource. That way, the programmer cannot forget to release the resource.
这篇关于我应该总是在函数末尾调用 vector clear() 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我应该总是在函数末尾调用 vector clear() 吗?
基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01