Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are iterators of standard containers DefaultConstructible?

Is this well formed?

int main() {
    std::deque< int >::iterator x; // Or any container.
}

Bonus questions:

  • What about auto y = x; which potentially copies uninitialized state?
  • What about … x = {}; which requires a non-explicit default constructor?
  • What about x == y if both are value-initialized (not default-initialized as illustrated)?
like image 408
Potatoswatter Avatar asked Dec 11 '22 09:12

Potatoswatter


1 Answers

Depends on the Iterator concept you're checking.

If it's a regular Iterator, which is just the absolute bare minimum to be called an iterator then the answer is no because it has to only meet the constructibility requirements of CopyConstructible, CopyAssignable, and Destructible. (§ 24.2.2 / 2)

However most container iterators meet the requirement of a BidirectionalIterator (except std::forward_list, which is an anomaly). All BidirectionalIterators in turn also meet the requirement of ForwardIterator, which meets the requirements of InputIterator (quite a mouthful).

The requirements for ForwardIterator explicitly state:

A class or pointer type X satisfies the requirements of a forward iterator if

— X satisfies the requirements of an input iterator (24.2.3),

— X satisfies the DefaultConstructible requirements (17.6.3.1),

§ 24.2.5 / 1 in N3376

So yes, this is a valid assumption.

You can find the iterator requirements in § 24.2 but they're nicely summarised in cppreference

like image 142
Rapptz Avatar answered Feb 20 '23 03:02

Rapptz