C++核心准则ES.24: 使用unique_ptr管理指针
共 1220字,需浏览 3分钟
·
2020-04-27 23:22
ES.24: Use a unique_ptr
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<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
觉得本文有帮助?请分享给更多人。
关注微信公众号【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!