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

标签 c++ c++11 std

我做了一些关于定义显式构造函数的研究( link1link2link3link4link5 )。

但对我来说,为什么将 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/

相关文章:

php - 构建C++共享库,.so被激活,等待PHP网页调用

C++:如何在 iOS 中已有的 MFC 应用程序中重用加密的 Sqlite 数据库

c++ - 让 foo(derived_object) 调用 foo(Base const&) 而不是模板函数?

c++ - 在 C++ 中重载 setter/getter ?

c++ - 使用带有 STL 容器的 boost.serialization 作为模板参数

c++ - 如何将 future 转移到 lambda 表达式中

c++ - 有没有一种安全的方法可以同时使用 C++11 智能指针和原始指针接口(interface)?

c++ - 在共享库中使用重载的new/delete和STL

c++ - 计算结构 vector 中的匹配项

c++ - 通过 std::rel_ops 特化 std::greater