智慧指標練習題 (Practice - Smart Pointers)

Question 1 - unique_ptr 的所有權語意 [recall]

同事寫下 auto p2 = p1;p1std::unique_ptr<Widget>)想「備份」指標,接著又問你若改成 auto p2 = std::move(p1); 之後 p1 會是什麼狀態。

Question 2 - custom deleter 與 unique_ptr 大小 [recall]

你需要在 delete 前先寫 log,猶豫該用一般函式(function pointer)還是無捕獲 lambda 當 std::unique_ptr 的 custom deleter——兩者對指標物件大小的影響為何?

Question 3 - 工廠函式的回傳型別設計 [application]

你為 Investment 階層(Stock/Bond/RealEstate)設計工廠函式,deleter 會以 Investment* 刪除物件,且部分呼叫者之後想共享所有權——該回傳哪種智慧指標?基底類別要注意什麼?

Question 4 - shared_ptr 的成本清單 [recall]

面試官要你列出 std::shared_ptr 相對 raw pointer 的主要成本,並回答「指定 custom deleter 後 shared_ptr 物件會變大嗎?」

Question 5 - control block 的建立規則 [recall]

快問快答:以下哪些建構方式會建立新的 control block——std::make_shared、從 std::unique_ptr 建構、傳入 raw pointer、傳入既有的 std::shared_ptrstd::weak_ptr

Question 6 - emplace_back(this) 的隱藏炸彈 [analysis]

Code review 時你看到 void Widget::process() { processedWidgets.emplace_back(this); }(容器型別為 std::vector<std::shared_ptr<Widget>>),程式可編譯也常常正常運作——請分析何時會爆炸、為什麼,以及完整的修正方案。

Question 7 - expired 檢查與安全存取 [recall]

為什麼「先呼叫 wpw.expired() 確認沒過期、再自行取值」不是安全的存取方式?正確的兩種做法與其 expired 行為各是什麼?

Question 8 - weak_ptr 的使用場景與樹狀結構 [recall]

說出 std::weak_ptr 的三大典型使用場景;另外,在嚴格階層式的樹狀結構中,parent→child 與 child→parent 的連結分別該用什麼指標?

Question 9 - 回指指標選型 [application]

資料結構中 A 與 C 各以 std::shared_ptr 共享 B 的所有權,現在 B 需要一個回指 A 的指標——請在 raw pointer、std::shared_ptrstd::weak_ptr 三者中選擇並說明另外兩者的缺陷。

Question 10 - make functions 的三大優點 [recall]

主管問你為何 code base 規定優先用 std::make_unique / std::make_shared 而非直接 new——請列出三個理由,並指出 std::make_unique 加入標準的版本。

Question 11 - 參數求值順序與資源洩漏 [analysis]

呼叫 processWidgetshared_ptr<Widget>(new Widget, cusDel), computePriority(); 在某些編譯器下會洩漏記憶體——請分析編譯器允許的執行順序如何導致洩漏、為何此處不能用 make_shared 補救,以及兼顧例外安全與效能的正確寫法。

Question 12 - make functions 的括號行為 [recall]

auto upv = std::make_unique<std::vector<int>>(10, 20); 建出的 vector 內容是什麼?若真的想要 {10, 20} 兩個元素該怎麼辦?

Question 13 - Pimpl 編譯錯誤修復 [application]

你把 Widget 改成 Pimpl(header 內 struct Impl; std::unique_ptr<Impl> pImpl;,未宣告解構子),客戶端寫 Widget w; 時編譯器抱怨「sizeof/delete applied to incomplete type」——請解釋原因並給出修法。

Question 14 - Pimpl 換用 shared_ptr 的差異 [recall]

若 Pimpl 的 pImpl 改用 std::shared_ptr<Impl>,還需要「header 宣告、實作檔定義」特殊成員函式的儀式嗎?為何實務上仍應選 std::unique_ptr