Returning vs. using a reference parameter [duplicate] - c++

This question already has answers here:
Which is more efficient: Return a value vs. Pass by reference?
(7 answers)
Closed 1 year ago.
This is really bugging me, coming from a C# background.
Sometimes, I see functions written like this:
int computeResult();
This is what I'm used to. But then I see them written like this:
void computeResult(int &result);
I find this strange. What benefits does the second method have over the first, if any? There must be something, since I see it all the time.

There are two common reasons for such non-const reference parameters:
You may need multiple "out" parameters in a function, and using reference parameter(s) allows for this.
Your object may be expensive to copy, and so you pass in a reference that will be mutated rather than returning an object that may get copied as part of the return process. Expensive-to-copy objects may include standard containers (like vector) and objects that manage heap memory where an allocation-copy-deallocate sequence would occur. Note that compilers are getting really good at optimizing away these copies when possible and so this reason has less import than it used to.
EDIT: I should clarify that even in C++ the specific example you've provided with a single builtin type reference parameter is pretty atypical. In such cases a return value is almost always preferred.

Related

Avoid non-const reference parameters [duplicate]

This question already has an answer here:
c reference semantic isn't explicit in caller's code
(1 answer)
Closed 7 years ago.
I come across this output param convention, which favours pointers than references.
"Within function parameter lists all references must be const:
void Foo(const string &in, string *out);
In fact it is a very strong convention in Google code that input arguments are values or const references while output arguments are pointers. Input parameters may be const pointers, but we never allow non-const reference parameters except when required by convention, e.g., swap()."
That seems somewhat different to the accepted answer to this question, which says references should be used instead, unless the function involves some pointer arithmetic.
So I wonder if this input param is const reference, output param is pointer is just a matter of google-style, or it is a more generally accepted practice (to avoid non-const reference parameters).
You don't mention the rationale for this coding practice. The main reason I'm aware of is that it makes it clearer what's getting written when you scan your eyes over a block of code. Even if you don't remember exactly what every called function does, you can still tell when a variable is being modified, because you'll see its address being passed.
Also, changing a function to sometimes modify one of its parameters can't silently break other code. You have to go to every call site and call by pointer. Presumably you'll notice if one of the call sites needs you to not change that parameter there.
I can't speak to how widely adopted or loved this convention is, but that is the reasoning behind it, as far as I'm aware.
It can potentially lead to slightly less optimal compiler output. A call-by-reference means that callers can assume that only the actual variable was modified, and no pointer-arithmetic was done to modify other elements of the same array. (Unless you have cross-file compilation, the compiler can't know the pointer arg to the called function isn't treated as an array.)

Pass arguments as std::string or const std::string&? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is it better in C++ to pass by value or pass by constant reference?
I thought about this while writing a file system.
vector<string> getFiles(string path);
vector<string> getFiles(const string& path);
What one is faster? What one is more elegant?
Obviously path will never be changed in the getFiles method.
Bonus: I'm using C++11. Is there a way move semantics would speed everything up?
Golden Rule:
"Always Pass by const reference by default."
This should be your default choice when passing function arguments. You chose other options as per the situation demands.
It is always more efficient for custom classes.
It is more intuitive to the user.
The canonical answer in your situation would be to pass the argument by const&, both for reasons of performance (it is guaranteed to avoid copying the string) and because you document intent. The former is only important if you have profiled your code and determined that passing the string is a bottleneck - if it isn't, you're mostly looking at "best practises" rather than making a big performance difference.
However to me, if I look at the signature of your function, the second one clearly states "I will only read your parameter and not do anything to it", whereas the first one pretty much states that you will be doing something to the parameter, even though your changes will not be visible to the outside as you are working on a copy of the parameter.
There is also the added advantage that passing the argument by const reference avoids memory allocations, which is handy if you are working on a system that doesn't have infinite memory (ie, all of them).
You're likely better off with the by-value parameter. See this post, Want Speed? Pass by Value, for detailed reasons. Basically, you give the caller and/or compiler more flexibility in how your function can be called. Using const& enforces what used to be a C++98 best-practice, but can work against move semantics in C++11.

Transmit parameter by value or by reference in C++? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Pass by reference more expensive than pass by value
I want to know which is better, sending parameters by value or by reference in C++. I heard that there are cases where sending by value is faster than sending by reference. Which are these cases?
Thanks
As a general rule, you should pass POD types by value and complex types by const reference.
That said, a good place where you pass complex types by value is where you would need a copy of the object inside the function anyway. In that case, you have two choices:
pass the argument as a const reference and create a local copy inside the function
pass the argument by value (the compiler creates the local copy).
The second option is generally more efficient. For an example, see the copy&swap idiom.
The obvious case is when the parameter is equal to or smaller than a pointer in size and trivial to copy -- then you would pass by value. However, this is a age-old discussion and quite a long answer is required to answer it correctly for a given architecture. There are also many corner cases (e.g. RVO).
There's more to the question than speed -- semantics should be your first priority.
See also: Is it better in C++ to pass by value or pass by constant reference?

Difference between "MyClass& func1(void)" and "MyClass* func2(void)" [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What is the proper way to return an object from a C++ function ?
Hi there,
i would like to know whats the difference between the following two functions with respect to the return types?
MyClass& func1(void)
MyClass* func2(void)
I always thought this would be the same?
Heinrich
The first one is only capable of returning a reference to a single object and may not be null. Or rather, it should not be null.
The second one may be returning the pointer to a single object, or an array of objects.
In cases where you wish to return a single object that cannot be null, #1 tends to be the preferred form. In cases where a null can be returned #2 has to be used. Some APIs don't return references at all (like QT).
This is strictly a syntactic difference however. These two types are handled exactly the same in the compiled code: a pointer to the object (or array) will be used. That is, strictly speaking, the reference notation & adds no new semantic functionality over a normal pointer.
(This perhaps just summarizes what the other people wrote)
the first one returns reference to an object (or its address). The other one returns pointer, not reference
Major difference: the second one can return NULL

Pass by Reference v. Pass by Pointer -- Merits? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
When pass-by-pointer is preferred to pass-by-reference in C++?
Are there benefits of passing by pointer over passing by reference in C++?
How to pass objects to functions in C++?
Hi all,
I'm working to develop a large object oriented c++ application framework as part of my chemical engineering graduate research.
I find that many of my functions take pointers to custom objects or STL objects. I find that in terms of writing code, this makes it harder to access functions or variables stored within.
Aside from simplicity, though, is there any advantages/disadvantages to passing by reference v. passing by pointer?
If there is an advantage to one over the other, I'll probably look to refactor my code to uniformly use whatever approach is optimal. If there isn't I may still refactor to consistently use pass by reference for readability (i.e. not having to dereference)
Again I want to make the best decision as my framework is already 40+ files large, so I want to implement as uniform structure as I can, as early as I can, and with whatever the optimal method is.
Thanks in advance!
The main difference is that a reference cannot be NULL (at least not without some malicious programming). For syntactical sugar and when an argument is required, I'd pass by reference. If I had a situation where the argument were optional, I'd pass by pointer.
There are always exceptions. If it conforms to the current style, or due to things I have to do with it, it may be more convenient to have it as a pointer.
Prefer pass by reference. If for nothing else I do it because a reference simply can't be NULL. It puts an end to so many stupid bugs, debates, contract checks, memory responsibility questions, etc ...
FYI this was asked in a slightly diff way earlier today:
When to pass by reference and when to pass by pointer in C++?
Canonical advice is "pass by ref to const unless a v good reason for another choice".
If your choice is pointers vs. references, use references. They have all the advantages of pointers without the danger of dereferencing an uninitialized pointer.
And don't worry too much about implementing a uniform approach early-- in this case it really isn't difficult to go back and forth between the two (one function at a time) even when the code base is large.
Personally I like passing by pointer because it offers some level of consistency in my code. I automatically know that my object Foo is a pointer. The same would apply with a reference so be sure to pick one and stick with it.
While I like references, there are a few common cases where you can't use them:
You want to store an object reference/pointer in a member variable but don't want to require that object in your class constructor
You want to store an object reference/pointer in a member variable and change the instance at runtime
You want make an object parameter to a method or function optional
In my view, having a mix of references and pointers is pretty ugly, so I prefer pointers.