F.26 使用unique_ptr<T>代替指针传递所有权
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_ptr<Shape> get_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<Circle>(is); case kTriangle: return make_unique<Triangle>(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代替。
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】,轻松学习每一天!
有任何疑问,欢迎留言提问或讨论。
面向对象设计,面向对象编程,面向对象思考!
---来自腾讯云社区的---面向对象思考
微信扫一扫打赏
支付宝扫一扫打赏