Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

If you are using a simple type (int, unit...), it could be optimized by the compiler.

But if i is an iterator, you will create an unnecessary copy. Maybe a special treatment can be done for STL types. But in some other cases, expecting ++i's behavior when doing explicitly i++ would surprise the user.



But since the copy won't be used, the compiler should omit it even for class types, since it can assume the copy constructor has no side-effects (if the copy constructor is not trivial in the first place).


I don't see why the compiler is allowed to assume that. For example, the class might collect statistics on #allocations, log them (e.g. for debugging purposes), or the iterator might create new objects (e.g. when the iterator is iterating over a (potentially) infinite sequence that gets created in a database on the fly)

I think the compiler should prove that constructing and destroying the object doesn't have side effects before skipping those steps.


If you want your iterator to be fast, its implementation will be in a header file, at which point the C++ compiler can inline and omit the copy entirely.


Of course, but that isn't making an assumption, as the OP said the compiler might do.


https://en.wikipedia.org/wiki/Copy_elision

I used to wonder the same thing, but C++ is just weird in that way.


That's only partially related to topic at hand. Even in cases where copy elision takes place, and object is still constructed.

However, as was said before, any performant iterators ought to be header-only implementations, and if they have no side effects, I don't see why a compiler might not do away with the copy altogether.

Personally I always use the prefix increment (unless the other behaviour is needed).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: