C++核心準則ES.24: 使用unique_ptr(T)管理指針

ES.24: Use a unique_ptr<T> to hold pointers

ES.24: 使用unique_ptr<T>管理指針

 

Reason(原因)

Using std::unique_ptr is the simplest way to avoid leaks. It is reliable, it makes the type system do much of the work to validate ownership safety, it increases readability, and it has zero or near zero run-time cost.

使用std::unique_ptr是避免泄露的最簡單方法。它可靠,它使類型系統做更多的工作以便安全地驗證所有權,它可以增加可讀性,它的沒有(或接近沒有)運行時代價。

 

Example(示例)

 

void use(bool leak){    auto p1 = make_unique<int>(7);   // OK    int* p2 = new int{7};            // bad: might leak    // ... no assignment to p2 ...    if (leak) return;    // ... no assignment to p2 ...    vector<int> v(7);    v.at(7) = 0;                    // exception thrown    // ...}

If leak == true the object pointed to by p2 is leaked and the object pointed to by p1 is not. The same is the case when at() throws.

如果leak==true,p2指向的對象就會發生泄露,但p1指向的對象就不會。at()拋出異常時也一樣。

 

Enforcement(實施建議)

Look for raw pointers that are targets of new, malloc(), or functions that may return such pointers.

尋找new,malloc的結果直接賦值個原始指針,或者函數返回這樣的指針的情況。

 

原文鏈接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es24-use-a-unique_ptrt-to-hold-pointers

 


 

覺得本文有幫助?歡迎點贊並分享給更多的人。

閱讀更多更新文章,請關注微信公衆號【面向對象思考】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章