3

I did some research about defining explicit constructors (link1, link2, link3, link4, link5).

But for me it is still not obvious why std::list and std::iterator single argument constructors defined as explicit and in which practical case this definition may be helpful. Can you please bring some examples where this definition helps to avoid bugs. Thanks

explicit list(const _Alloc& _Al)
    : _Mybase(_Al)
    {   // construct empty list, allocator
    }

explicit back_insert_iterator(_Container& _Cont)
    : container(_STD addressof(_Cont))
    {   // construct with container
    }
Community
  • 1
  • 1
T M
  • 3,195
  • 2
  • 31
  • 52

1 Answers1

9

Is the following code good and self-explanatory? We copy-initialize list with an allocator, while people expect list's value_type elements to be inserted. Explicit constructors forbid such misuses.

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

or

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

myallocator<int> alloc;
f(alloc);
legends2k
  • 31,634
  • 25
  • 118
  • 222
ForEveR
  • 55,233
  • 2
  • 119
  • 133