我做了一些关于定义显式构造函数的研究( link1 、 link2 、 link3 、 link4 、 link5 )。
但对我来说,为什么将 std::list 和 std::iterator 单参数构造函数定义为显式以及在实际情况下该定义可能有用的原因仍然不明显。 您能否举出一些示例,说明此定义有助于避免错误。谢谢
explicit list(const _Alloc& _Al)
: _Mybase(_Al)
{ // construct empty list, allocator
}
explicit back_insert_iterator(_Container& _Cont)
: container(_STD addressof(_Cont))
{ // construct with container
}
最佳答案
下面的代码是否良好且不言自明?我们使用分配器复制初始化列表,而人们期望插入列表的 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);
关于c++ - 为什么 std::list 中的单参数构造函数定义为显式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32140114/