C++中的T*返回值有什么作用

发布时间:2021-11-25 16:13:37 作者:iii
来源:亿速云 阅读:223

本篇内容介绍了“C++中的T*返回值有什么作用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

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.

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

Enforcement(实施建议)

“C++中的T*返回值有什么作用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

推荐阅读:
  1. Android Java调用自己C++类库的实例讲解
  2. C++中怎么用strcmp比较两个字符串

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:如何理解服务器端类JSON性能

下一篇:C++为什么尽量避免定义默认操作

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》