Re: [問題] smart pointer 新手的小小問題
※ 引述《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:06, , 1F
02/28 21:06, 1F
→
02/28 21:08, , 2F
02/28 21:08, 2F
→
02/28 21:09, , 3F
02/28 21:09, 3F
→
02/28 21:09, , 4F
02/28 21:09, 4F
推
02/28 23:01, , 5F
02/28 23:01, 5F
→
03/03 22:51, , 6F
03/03 22:51, 6F
推
03/03 23:31, , 7F
03/03 23:31, 7F
→
03/03 23:33, , 8F
03/03 23:33, 8F
推
03/05 16:08, , 9F
03/05 16:08, 9F
→
03/05 22:21, , 10F
03/05 22:21, 10F
→
03/05 22:22, , 11F
03/05 22:22, 11F
→
03/05 22:23, , 12F
03/05 22:23, 12F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):