天天看點

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​​

繼續閱讀