Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are objects passed to functions C++, by value or by reference?

Tags:

c++

Coming from C#, where class instances are passed by reference (that is, a copy of the reference is passed when you call a function, instead of a copy of the value), I'd like to know how this works in C++. In the following case, _poly = poly, is it copying the value of poly to _poly, or what?

#include <vector>
using namespace std;

class polynomial {
    vector<int> _poly;
public:
    void Set(vector<int> poly);
};

void polynomial::Set(vector<int> poly) {
    _poly = poly;                             <----------------
}
like image 457
devoured elysium Avatar asked Jul 20 '09 20:07

devoured elysium


People also ask

Are objects passed by value or reference?

Object references are passed by value The reason is that Java object variables are simply references that point to real objects in the memory heap. Therefore, even though Java passes parameters to methods by value, if the variable points to an object reference, the real object will also be changed.

Does C use pass by value or reference?

C always uses 'pass by value' to pass arguments to functions (another term is 'call by value', which means the same thing), which means the code within a function cannot alter the arguments used to call the function, even if the values are changed inside the function.

Are objects passed by reference or value in C#?

By default, C# does not allow you to choose whether to pass each argument by value or by reference. Value types are passed by value. Objects are not passed to methods; rather, references to objects are passed—the references themselves are passed by value.

Are C functions pass by reference?

Pass by Reference A reference parameter "refers" to the original data in the calling function. Thus any changes made to the parameter are ALSO MADE TO THE ORIGINAL variable. Arrays are always pass by reference in C.


1 Answers

poly's values will be copied into _poly -- but you will have made an extra copy in the process. A better way to do it is to pass by const reference:

void polynomial::Set(const vector<int>& poly) {
    _poly = poly;                      
}

EDIT I mentioned in comments about copy-and-swap. Another way to implement what you want is

void polynomial::Set(vector<int> poly) { 
    _poly.swap(poly); 
}

This gives you the additional benefit of having the strong exception guarantee instead of the basic guarantee. In some cases the code might be faster, too, but I see this as more of a bonus. The only thing is that this code might be called "harder to read", since one has to realize that there's an implicit copy.

like image 91
rlbond Avatar answered Sep 30 '22 15:09

rlbond