为什么std::list中的单参数构造函数定义为显式

Why single argument constructors in std::list defined as explicit

本文关键字:构造函数 定义 参数 list std 为什么 单参数      更新时间:2023-10-16

我做了一些关于定义显式构造函数(link1, link2, link3, link4, link5)的研究。

但是对于我来说,std::list和std::iterator单参数构造函数被定义为显式的原因仍然不明显,在实际情况下,这个定义可能会有所帮助。你能举一些例子说明这个定义有助于避免bug吗?由于

explicit list(const _Alloc& _Al)
    : _Mybase(_Al)
    {   // construct empty list, allocator
    }
explicit back_insert_iterator(_Container& _Cont)
    : container(_STD addressof(_Cont))
    {   // construct with container
    }

下面的代码是好的和不言自明的吗?我们使用分配器复制初始化list,而人们期望插入list的value_type元素。显式构造函数禁止这种滥用。

myallocator<int> allocator;
std::list<int, myallocator<int> > lst = allocator;

void f(const std::list<int, myallocator<int> >& lst)
{
}
myallocator<int> alloc;
f(alloc);