简体   繁体   中英

Distinguishing Pass-by-Reference and Pass-by-Value

How are pass-by-reference functions typically distinguished from pass-by-value functions? 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.

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. 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. 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...).

It's typically preferred not to pass by non-const reference if possible and to use the second form. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM