C++核心準則ES.24: 使用unique

C++核心準則ES.24: 使用unique_ptr <div class=
管理指針">

ES.24: Use a unique_ptr to hold pointers

ES.24: 使用unique_ptr管理指針

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(示例)

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

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

覺得本文有幫助?請分享給更多人。

關注微信公眾號【面向對象思考】輕鬆學習每一天!

面向對象開發,面向對象思考!

C++核心準則ES.24: 使用unique_ptr <div class=
管理指針">


分享到:


相關文章: