您的位置 首页 > 腾讯云社区

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 条评论)
   
验证码: