0
点赞
收藏
分享

微信扫一扫

C++核心准则边译边学-F.42 T*返回值应该只用来指明位置


F.42: Return a ​​T*​​ to indicate a position (only)

F.42:T*返回值应该只用来指明位置

 

Reason(原因)

That's what pointers are good for. Returning a ​​T*​​ to transfer ownership is a misuse.

这是指针的强项。使用T*返回所有权是错误的用法。

Example(示例)

 

Node* find(Node* t, const string& s)  // find s in a binary tree of Nodes{    if (!t || t->name == s) return t;    if ((auto p = find(t->left, s))) return p;    if ((auto p = find(t->right, s))) return p;    return nullptr;}

If it isn't the ​​nullptr​​​, the pointer returned by ​​find​​​ indicates a ​​Node​​​ holding ​​s​​. Importantly, that does not imply a transfer of ownership of the pointed-to object to the caller.

如果返回值不为nullptr,则find返回的指针表示持有s的Node。重要的是,它不包含向调用者传递指针所指向的对象的所有权的含义。

Note(注意)

Positions can also be transferred by iterators, indices, and references. A reference is often a superior alternative to a pointer if there is no need to use ​​nullptr​​ or if the object referred to should not change.

位置也可以通过迭代器,索引和引用传递。如果不需要使用nullptr或者对象不希望被修改,引用通常是比指针更好的选择。

Note(注意)

Do not return a pointer to something that is not in the caller's scope; see F.43.

不要返回指向不属于调用者范围的某物的指针。

See also: discussion of dangling pointer prevention

参见:关于防止悬空指针的讨论。

Enforcement(实施建议)

  • Flag​​delete​​, ​​std::free()​​, etc. applied to a plain ​​T*​​. Only owners should be deleted.
    标示运用在直接指针上的delete,std::free()等操作。只用所有者才可以删除。
  • Flag​​new​​, ​​malloc()​​, etc. assigned to a plain ​​T*​​. Only owners should be responsible for deletion.
    标记将结果分配个直接指针的new,malloc()等处理。只有所有者才有销毁的责任。

 


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

举报

相关推荐

0 条评论