Effective Modern C++ === ## 條款 18:使用 std::unique_ptr 管理單一所有權的資源 - unique_ptr **不允許 copy**,因為會造成兩個 unique_ptr 各自認為自己要負責清除 resource。因此,unique_ptr 是只允許 move 的 型別,預設的清除行為是對 raw pointer 執行 delete。 - 可以在 create unique_ptr 時提供 custom deleter,參考如下: ```clike= auto custom_deleter = [](Base* base) // lambda expression. { // sth to release... }; template<typename... Ts> // simple factory pattern. std::unique_ptr<Base, decltype(custom_deleter)> GetPtr(Ts&&... params) { std::unique_ptr<Base, decltype(custom_deleter)> ptr; ptr.reset( new Derived( std::forward<Ts>(params)... ) ); return ptr; } ``` user 透過 `auto ptr = GetPtr(args);` 來取得 unique_ptr,也不用擔心 resource 的清理問題。上述程式碼有幾個需要注意的地方: 1. custom deleter 只接受要被清除的 object 的 raw pointer。 2. 使用 lambda 做為 custom deleter 的做法也較有效率,原因是跟其他的寫法比起來 e.g. function pointer 或是一般的 function object,lambda 不需要額外的空間成本。 - unique_ptr 也可以簡單且有效率的轉換為 shared_ptr: `std::shared_ptr<Base> ptr = GetPtr(args);` ###### tags: `Effective modern C++`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up