std :: list< int>的默认构造函数是否可以扔? [英] Can the default constructor of std::list<int> throw?

查看:115
本文介绍了std :: list< int>的默认构造函数是否可以扔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我快速浏览了C ++标准和在线C ++参考,但是找不到这个简单问题的答案:

I had a (quick) look into the C++ standard and into an online C++ reference, but I could not find an answer to this simple question:

std::list<int>的默认构造函数可以抛出吗?

Can the default constructor of std::list<int> throw?

如果是这样,为什么会抛出?

If so, why would it throw?

推荐答案

简短答案:可以,但是可以用相当安全的方式实现:

Short answer: it can, but it may be implemented in a way that is reasonably safe:

默认构造函数构造一个空列表,因此几乎不需要在进程中实际分配内存.大多数列表实现不会为空列表分配任何内存.

The default constructor constructs an empty list, so there is little need to actually allocate memory in the process. Most list implementations won't allocate any memory for an empty list.

但是,默认构造函数不是 really 真正的默认构造函数,因为它具有默认参数:explicit list(const Allocator& = Allocator());
Allocator本身是模板参数,因此,如果Allocator具有足够愚蠢的(或复杂的)实现提供抛出默认构造函数,则构造函数的 call 可能已经抛出.默认参数将引发.

However, the default constructor is not really a default constructor, since it has a defaulted argument: explicit list(const Allocator& = Allocator());
Allocator itself is a template argument, so the call of the constructor already might throw, if Allocator has a sufficiently dumb (or complex) implementation providing a throwing default constructor, i.e. if the construction of the default argument throws.

如果默认的构造函数Allocator不抛出,那么提供std::list的实现就很容易,该实现的默认构造函数也不会抛出.但是库实现者并不需要这样做.

If the default constructor of Allocator does not throw, it is realtively easy to provide an implementation of std::list whose default constructor won't throw either. But library implementors are not required to do so.

已更新:list必须存储给定分配器的副本,以便以后可以调用它.与我先前的主张相反,对Allocator的副本构造函数的最终调用可能不会抛出(第17.7.6.3.5节,请参见注释). list实现也不允许例如默认构造分配器,并在构造器中进行拷贝分配,因为这会破坏任何尝试将list与无法默认构造的分配器一起使用的代码.

Updated: The list has to store a copy of the given allocator to be able to call it later. Contrary to my prior claim, the resulting call to the copy constructor of Allocator may not throw (§17.6.3.5, see the comments). The list implementation is also not allowed to e.g. default-construct the allocator and do a copy assignment in the constructor, because that would break any code that tries to use the list with allocators that are not default-constructible.

这篇关于std :: list&lt; int&gt;的默认构造函数是否可以扔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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