Safe, Generic Programming

C++ Primer 4/e 在vector這裡有一個關鍵概念:『Programmers coming to C++ from C or Java might be surprised that our loop used != rather than < to test the index against the size of the vector. C programmers are probably also suprised that we call the size member in the for rather than calling it once before the loop and remembering its value.

C++ programmers tend to write loops using != in preference to < as a matter of habit. In this case, there is no particular reason to choose one operator or the other. We’ll understand the rationale for this habit once we cover generic programming in Part II.

Calling size rather than remembering its value is similarly unnecessary in this case but again reflects a good habit. In C++, data structures such as vector can grow dynamically. Our loop only reads elements; it does not add them. However, a loop could easily add new elements. If the loop did add elements, then testing a saved value of size would failour loop would not account for the newly added elements. Because a loop might add elements, we tend to write our loops to test the current size on each pass rather than store a copy of what the size was when we entered the loop.

As we’ll see in Chapter 7, in C++ functions can be declared to be inline. When it can do so, the compiler will expand the code for an inline function directly rather than actually making a function call. Tiny library functions such as size are almost surely defined to be inline, so we expect that there is little run-time cost in making this call on each trip through the loop.』

中文版的是這樣說:『C或Java程式員可能會對「在迴圈內使用 != 而非 < 來測試索引值和vector大小」感到驚訝。C程式員可能也會對「在for內呼叫size()而非在迴圈前呼叫一次並記住其值」感到驚訝。

C++程式員習慣上傾向使用 != 而較不喜歡使用 < 來寫迴圈。倒是沒有特別理由一定要選用某個運算子。第Ⅱ篇談到泛型編程(generic programming)後讀者就會瞭解這個習慣的緣由。



用 != 真得很令人訝異,而且一般來說我會習慣使用記住size,除非這個陣列或物件的size真的向作者說會變大或減少時,我才不會用記住的方式。不過如果size是用inline的方式而且執行期成本是這麼低的話,那變更習慣卻是沒什麼不好。