Re: [問題] 看Stroustrup 的C++後有不懂的問題想請教

看板C_and_CPP (C/C++)作者 (眠月)時間16年前 (2009/03/17 21:28), 編輯推噓0(003)
留言3則, 1人參與, 最新討論串3/3 (看更多)
回我知道的。 ※ 引述《allstarschh (allstars)》之銘言: : 我看的是Stroustrup的the C++ Programming lang : 然後有幾個問題想請教 : 1.在Chap3 3.11 Advice p.66 裡 第七條 : Using string rather than char* : 請問即使我對char * 用了簡單的strcat strcpy這些library : 會比string 還要來的慢嗎??? 嗯,對 std::string 比較快。 當初看到這點我也覺得很怪,所以就下去做了 benchmark, 後來發現 std::string 的效能的確比較好, 想了一下之後就知道原因:「因為 std::string 內部有保存字串的長度」 所以像是 strlen 這樣的操作,std::string 可以 O(1) 做完。 另外 strcat 或是 strcpy 的操作,std::string 也因為知道長度, 所以 code gen 的時候可以直接生出像是 MOVE 這樣效能好很多的碼。 (STL 裡面 copy 演算法也有用同樣的手法加速) 總之重點是「多知道字串長度,可以作很多事情」 缺點是你要多記一個長度,記憶體就會用的會比 char* 多。 : 3. 在10.4.6.2 Member Constants p249 : 他說可以initialize a static integral constant member : 為什麼只有int 可以 float那些為什麼不行呢??? 原因我忘了,但是別的型態要直接指定在技術上也沒有難度, 沒記錯的話《C++ Template Metaprogrammin》裡面有講到這點, 標準的這個規定已經算是不和時宜了,以後有機會拿掉這個限制。 -- To iterate is human, to recurse, divine. 遞迴只應天上有, 凡人該當用迴圈.   L. Peter Deutsch -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.160.110.89

03/17 21:29, , 1F
另外 std::string 也可以實作 small string optimization
03/17 21:29, 1F

03/17 21:30, , 2F
跟 copy on write optimization,效能會好上更多
03/17 21:30, 2F

03/17 21:30, , 3F
不過 copy on write 現在少用了.. STLport 有實作
03/17 21:30, 3F
文章代碼(AID): #19lwMBDh (C_and_CPP)
文章代碼(AID): #19lwMBDh (C_and_CPP)