C++核心准则R.20: 使用unique_ptr或者shared_ptr表示所有权
R.20: Use unique_ptr or shared_ptr to represent ownership
R.20: 使用unique_ptr或者shared_ptr表示所有权
Reason(原因)
They can prevent resource leaks.
使用它们可以防止资源泄露。
Example(示例)
Consider(考虑以下代码):
void f()
{
X x;
X* p1 { new X }; // see also ???
unique_ptr p2 { new X }; // unique ownership; see also ???
shared_ptr p3 { new X }; // shared ownership; see also ???
auto p4 = make_unique(); // unique_ownership, preferable to the explicit use "new"
auto p5 = make_shared(); // shared ownership, preferable to the explicit use "new"
}
This will leak the object used to initialize p1 (only).
这段代码中(只有)用来初始化p1的对象会发生泄露。
Enforcement(实施建议)
(Simple) Warn if the return value of new or a function call with return value of pointer type is assigned to a raw pointer.
(简单)如果new操作的返回值或者返回指针类型的函数调用的返回值被赋值给一个原始指针,发出警告。
原文链接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r20-use-unique_ptr-or-shared_ptr-to-represent-ownership
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!
评论