C++核心准则ES.24: 使用unique_ptr(T)管理指针

网友投稿 619 2022-10-13

C++核心准则ES.24: 使用unique_ptr(T)管理指针

C++核心准则ES.24: 使用unique_ptr(T)管理指针

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

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 // ...}

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

觉得本文有帮助?欢迎点赞并分享给更多的人。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Mybatis中特殊SQL的执行
下一篇:C++核心准则ES.27:使用std::array或者stack_array在堆栈上构建数组
相关文章

 发表评论

暂时没有评论,来抢沙发吧~