我应该总是在函数的结尾调用向量clear()? [英] Should I always call vector clear() at the end of the function?

查看:197
本文介绍了我应该总是在函数的结尾调用向量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 在< a href =http://www.stroustrup.com/bs_faq2.html#finally =nofollow>为什么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.

这篇关于我应该总是在函数的结尾调用向量clear()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆