且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我应该总是在函数末尾调用 vector clear() 吗?

更新时间:2022-12-13 23:17:35

如果我们看看 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.