Nella Guida di stile di Google C ++ si dice:
Preincrement and Predecrement
Use prefix form (
++i) of the increment and decrement operators with iterators and other template objects.When a variable is incremented (
++iori++) or decremented (--iori--) and the value of the expression is not used, one must decide whether to preincrement (decrement) or postincrement (decrement).When the return value is ignored, the "pre" form (
++i) is never less efficient than the "post" form (i++), and is often more efficient. This is because post-increment (or decrement) requires a copy ofito be made, which is the value of the expression. Ifiis an iterator or other non-scalar type, copyingicould be expensive. Since the two types of increment behave the same when the value is ignored, why not just always pre-increment?The tradition developed, in C, of using post-increment when the expression value is not used, especially in for loops. Some find post-increment easier to read, since the "subject" (
i) precedes the "verb" (++), just like in English.For simple scalar (non-object) values there is no reason to prefer one form and we allow either. For iterators and other template types, use pre-increment.
Non devo assolutamente essere d'accordo con "Quando il valore di ritorno viene ignorato, il form" pre "( ++i ) non è mai meno efficiente del modulo" post "( i++ ), ed è spesso più efficiente Questo perché il post-incremento (o decremento) richiede una copia di i da produrre, che è il valore dell'espressione. "
Almeno quando si tratta di puntatori (e i registri dei puntatori possono essere usati come numeri interi).
Tornando ai miei giorni dell'hardware, c'erano molte istruzioni macchina che avevano una forma di modalità di indirizzamento con post-incremento, post-decremento e pre-decremento integrati. Le modalità post-inc e post-dec costano 0 cicli di istruzione supplementari più di nessun incremento. L'incremento si è verificato dopo che l'istruzione è stata eseguita mentre il prossimo opcode veniva recuperato, ma il pre-dec ha richiesto un ciclo di istruzioni aggiuntivo prima che il registro venisse utilizzato. Quindi, non lo capisco davvero. Qualcuno può spiegare il caso di Google a me?