首頁 / CompScience / Programming / Languages / C_and_CPP / Safe, Generic Programming

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()而非記住其值」在這裡同樣也非必要,但再次反映一個良好的習慣。在C++,vector這一類資料結構可以動態成長。雖然此處的迴圈只讀取元素,並沒有增加元素,然而迴圈內的確輕易可以加入元素。果真如此,那麼測試前儲存size就會出錯,迴圈將因此不處理新加入的元素。由於迴圈可能加入元素,所以我們傾向每次測試當下的size,而非紀錄進入的迴圈前的size。

如同第7章即將看到,C++函式可宣告為inline。一旦如此,編譯器會把inline函式的程式碼當下展開,而非產生一個函式呼叫。小型函式如size()幾乎肯定會被定義為inline,所以可預期「每個迭代都呼叫一次」只帶來很小的執行期成本。』

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

Print Friendly, PDF & Email
馬上成為工作達人的Fans

About ㄚ琪

工作達人Fun Taiwan的創辦者及總編,可以在這裡更認識他。

發表迴響

你的電子郵件位址並不會被公開。 Required fields are marked *

*

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料

Scroll To Top