F.26: Use a unique_ptr
F.26 使用unique_ptr
Reason(原因)
Using unique_ptr is the cheapest way to pass a pointer safely.
使用unique_ptr是成本最低的安全地传递指针的方式。
See also: C.50 regarding when to return a shared_ptr from a factory.
参见:C.50 关于什么时候从工厂返回shared_ptr。
Example(示例)
unique_ptrget_shape(istream& is) // assemble shape from input stream
{
auto kind = read_header(is); // read header and identify the next shape on input
switch (kind) {
case kCircle:
return make_unique(is);
case kTriangle:
return make_unique(is);
// ...
}
}
译者注:关于unique_ptr,可以参照:https://mp.weixin.qq.com/s/wgc8p1Pw9GD5LIx1C33wxQ
Note(注意)
You need to pass a pointer rather than an object if what you are transferring is an object from a class hierarchy that is to be used through an interface (base class).
如果你希望传递的是将会通过(基类)接口使用的,继承关系中的类对象时,应该传递指针而不是对象。
译者注:这句话的意思应该是:如果只是传递一个用于调用的接口,直接使用指针式最好的方式。
Enforcement(实施建议)
(Simple) Warn if a function returns a locally allocated raw pointer. Suggest using either unique_ptr or shared_ptr instead.
(简单)如果函数返回本地分配的裸指针,报警并建议使用unique_ptr或者shared_ptr代替。
觉得本文有帮助?请分享给更多人。
更多更新文章,欢迎关注微信公众号【面向对象思考】
面向对象设计,面向对象编程,面向对象思考!
本文来自投稿,不代表本人立场,如若转载,请注明出处:http://www.souzhinan.com/kj/202639.html