0
点赞
收藏
分享

微信扫一扫

C++核心准则边译边学-F.26 使用unique_ptr(T)代替指针传递所有权


F.26: Use a ​​unique_ptr<T>​​ to transfer ownership where a pointer is needed

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代替。


阅读更多更新文章,请关注微信公众号【面向对象思考】

举报

相关推荐

0 条评论