更新时间:2022-12-13 23:09:12
如果我们看一下 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结构?:
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.