[英]Distinguishing Pass-by-Reference and Pass-by-Value
How are pass-by-reference functions typically distinguished from pass-by-value functions? pass-by-reference函数通常如何区分pass-by-value函数? For example:
例如:
template <typename T>
void sort(std::vector<T>& source); // Sorts source.
// Versus...
template <typename T>
std::vector<T> sort(std::vector<T> source); // Returns a sorted copy of source.
These two functions are ambiguous; 这两个功能含糊不清; one of them must be either renamed or removed completely.
其中一个必须重命名或完全删除。
How can this situation be avoided? 如何避免这种情况? Should one form be preferred over the other?
一种形式应该优先于另一种吗? Or are there any common naming guidelines to distinguish them?
或者是否有任何共同的命名准则来区分它们?
Can't you just give them different names? 你不能给他们不同的名字吗? I would name the functional version
sorted
, for example. 例如,我会将功能版本命名为已
sorted
。
Just because you can overload functions (or function templates in this case) does not mean you have to. 仅仅因为你可以重载函数(或者在这种情况下是函数模板)并不意味着你必须这样做。
By the way, you can implement the "functional version" in terms of the "imperative version": 顺便说一句,您可以根据“命令式版本”实现“功能版本”:
template <typename T>
void sort(std::vector<T>& source)
{
// sort in place
}
template <typename T>
std::vector<T> sorted(std::vector<T> copy)
{
sort(copy);
return copy;
}
FredOverflow hit the nail on the head. FredOverflow击中了头部。 However, to answer your question "Or are there any common naming guidelines to distinguish them?"
但是,要回答您的问题“或者是否有任何共同的命名准则来区分它们?” Just make sure you are consistent.
只要确保你是一致的。 For example something like SortCopy for the second function name in your example.
例如,在您的示例中,第二个函数名称的SortCopy之类的东西。 It doesn't matter if it is SortCopy, SortCpy, Sort_Copy.. what does matter is that throughout your code, you are consistent (eg- all functions that act on a copy have the "Copy" prefix- not one having Copy, the next Cpy, etc...).
如果它是SortCopy,SortCpy,Sort_Copy并不重要..重要的是在整个代码中,你是一致的(例如 - 所有作用于副本的函数都有“复制”前缀 - 没有一个具有复制,下一个Cpy等...)。
It's typically preferred not to pass by non-const reference if possible and to use the second form. 如果可能,通常优选不通过非const引用并使用第二种形式。 This is because firstly, the second sort plays much nicer if you want to pass the return value to another function, and secondly, because the compiler's optimizer will deal with unnecessary copying in most cases, and thirdly because having a reference in prevents any kind of TMP from detecting the fact that it's actually a return value, and prevents the use of the function in any kind of function object context.
这是因为首先,如果你想将返回值传递给另一个函数,第二个排序会更好,其次,因为编译器的优化器在大多数情况下会处理不必要的复制,第三个因为有一个引用可以防止任何类型的TMP从检测到它实际上是一个返回值的事实,并阻止在任何类型的函数对象上下文中使用该函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.