c++pass-by-referencepass-by-value

By default, are objects passed by value or by reference?


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>

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

Solution

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