Thursday, June 26, 2008

Safe, Generic Programming

C++ Primer 4/e in vector there is a key concept:『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 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.』
Chinese translation is said:『C或Java程式員可能會對「在迴圈內使用 != 而非 < 來測試索引值和vector大小」感到驚訝。C程式員可能也會對「在for內呼叫size()而非在迴圈前呼叫一次並記住其值」感到驚訝。
C++程式員習慣上傾向使用 != 而較不喜歡使用 < 來寫迴圈。倒是沒有特別理由一定要選用某個運算子。第Ⅱ篇談到泛型編程(generic programming)後讀者就會瞭解這個習慣的緣由。
「呼叫size()而非記住其值」在這裡同樣也非必要,但再次反映一個良好的習慣。在C++,vector這一類資料結構可以動態成長。雖然此處的迴圈只讀取元素,並沒有增加元素,然而迴圈內的確輕易可以加入元素。果真如此,那麼測試前儲存size就會出錯,迴圈將因此不處理新加入的元素。由於迴圈可能加入元素,所以我們傾向每次測試當下的size,而非紀錄進入的迴圈前的size。
如同第7章即將看到,C++函式可宣告為inline。一旦如此,編譯器會把inline函式的程式碼當下展開,而非產生一個函式呼叫。小型函式如size()幾乎肯定會被定義為inline,所以可預期「每個迭代都呼叫一次」只帶來很小的執行期成本。』
Using != is very suprised to me.And I generally used to remember size unless the array or object will increase or decrease as the author said.I will not use remember size.But if size use the method of the inline and the runtime cost is very low.Then changing the habit actually may be not bad.

achi's Blog

No comments: