Re: [問題] smart pointer 新手的小小問題

看板C_and_CPP作者 (ITSST)時間9年前 (2015/02/28 20:07), 編輯推噓3(309)
留言12則, 6人參與, 最新討論串2/2 (看更多)
※ 引述《MashiroKinji (MashiroKinji)》之銘言: : 既上次向各位前輩討教關於的問題 : https://www.ptt.cc/bbs/C_and_CPP/M.1424809447.A.FBD.html : 小弟開始決定使用智能指標 : 想請問一下使用智能指標跑for的時候 : std::vector<std::unique_ptr<MyClass>> vector; : for (int i = 0; i < 10;i++) : { : std::unique_ptr<MyClass> temp(new MyClass(i)); : vector.push_back(std::move(temp)); : } : //----- 可以改用emplace: for (int i = 0; i < 10;i++) { vector.emplace_back(new MyClass(i)); } : (1) : for (std::vector<std::unique_ptr<MyClass>>::iterator i = vector.begin(); i : != vector.end(); i++) : { : i->get()->Print(); 這裡不需要呼叫get(), 可以改成 (*i)->Print()。 : } : (2) : for (int i = 0; i < vector.size(); i++) : { : vector[i]->Print(); : } 都很不專業, (1)除了太長,若以後型態有稍微改到,這邊也要更新程式, 例如MyClass改用YourClass、std::unique_ptr改用std::shared_ptr、 std::vector改用std::deque、…。 (2)宣告i的型態int與vector.size()回傳值的型態不同、signed不一致, 可能會造成執行期的漏洞。 在C++11裡最方便的就是可以使用range for: for (auto &obj : vector) { obj->Print(); } : //----- : vector.clear(); : 想請問一下(1),(2)哪個做法會比較好呢? : 感覺(1)的方法超長的看得好辛苦... : (2)的話又感覺不是很專業!? : 另外同樣的功能用傳統的指標去做整體程式碼就看起來很簡潔 : 而且在push_back的時候還可以 : vector.push_back(new MyClass(i)); : 比起要創建一個unique_ptr然後再用move傳送 : 感覺還要快好多 又是感覺,是快多少呢? 有數據嗎? 我沒測試過,但Effective Modern C++有提到: std::unique_ptrs are the same size as raw pointers, and for most operations (including dereferencing), they execute exactly the same instructions. This means you can use them even in situations where memory and cycles are tight. If a raw pointer is small enough and fast enough for you, a std::unique_ptr almost certainly is, too. : 是不是在使用智能指標後就要有著和使用Java的垃圾回收機制 : 一定要有著效能降低的準備?? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.62.205.151 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1425125220.A.E57.html

02/28 21:08, , 2F
g++ 4.9.2 -O3 編出來的結果
02/28 21:08, 2F

02/28 21:09, , 3F
基本上用iterator、range-based for或是raw pointer的結果
02/28 21:09, 3F

02/28 21:09, , 4F
都是一樣的 foo2多了index反而更慢
02/28 21:09, 4F

02/28 23:01, , 5F
感謝大大的指教
02/28 23:01, 5F

03/03 22:51, , 6F
如果emplace_back丢例外會memory leak,建議用make_unique
03/03 22:51, 6F

03/03 23:31, , 7F
make_unique 是 C++14 才有的東西, 要夠新的編譯器才有
03/03 23:31, 7F

03/03 23:33, , 8F
不過 C++11 範圍裡確實沒什麼好解法就是...
03/03 23:33, 8F

03/05 16:08, , 9F
03/05 16:08, 9F

03/05 22:21, , 10F
C++11可以自己定義make_unique,但用VS2012的就很尷尬,沒有
03/05 22:21, 10F

03/05 22:22, , 11F
variadic template可以用在make_unique
03/05 22:22, 11F

03/05 22:23, , 12F
VS2012很討厭,一堆C++11重要的feature沒實現,要VS2013才有
03/05 22:23, 12F
文章代碼(AID): #1KyQzavN (C_and_CPP)
文章代碼(AID): #1KyQzavN (C_and_CPP)