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

本篇内容介绍了“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(实施建议)

  • 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()等处理。只有所有者才有销毁的责任。

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