【问题标题】:Why single argument constructors in std::list defined as explicit为什么 std::list 中的单参数构造函数定义为显式
【发布时间】:2015-11-15 09:16:29
【问题描述】:

我做了一些关于定义显式构造函数的研究(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
    }

【问题讨论】:

    标签: c++ c++11 std


    【解决方案1】:

    以下代码是否良好且不言自明?我们使用分配器复制初始化列表,而人们希望插入列表的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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-09
      • 2017-07-07
      • 2016-11-01
      • 2019-01-18
      • 2014-11-08
      • 2019-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多