Markus Mayr
Markus Mayr

Reputation: 4118

Usefulness of post-incrementing a weakly_incrementable?

I studied the weakly_incrementable concept recently and I am wondering what the post-increment operator is good for, given that the concept does not define any requirements for the result of the operation.

Is it actually okay to return void for operator++(int)?

void operator++(int) { ++(*this); }

It seems in line with the other requirements of the concept (like that it does not have to be copyable) and also with the fact that the incrementable concept introduces requirements that make i++ useful, but in that case I am wondering why i++ is defined by the concept at all. After all, when you require something to implement the weakly_incrementable concept, you can always use ++i instead of i++ because

  1. you can't rely on i++ having any useful properties, apart from those already provided by ++i but
  2. i++ may be more inefficient (when it creates a copy of the iterator, for example).

Upvotes: 4

Views: 241

Answers (1)

metalfox
metalfox

Reputation: 6751

That design decission is documented in P0541.

Is it actually okay to return void for operator++(int)?

Yes. It is. A specific straw poll was taken, as stated in the paper.

Removing the postfix increment in its entirety was also considered but:

The authors of the Ranges TS strongly prefer keeping the postfix increment operator for input iterators. Consider the following fairly common (anti-)pattern:

for (auto i = v.begin(); i != v.end(); i++) {
// ...
}

Aside from concerns over the cost of post-increment, there is nothing wrong with this code per se, and the authors see no compelling reason to break it. And by permitting i++ to return void, we would actually be mitigating the performance problem.

Upvotes: 4

Related Questions