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

Based on C #, where instance instances are passed by reference (that is, a copy of the link is passed when the function is called instead of a copy of the value), I would like to know how this works in C ++. In the following case, _poly = poly, does the poly value copy 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;                             <----------------
}
+5
source share
8 answers

polythe values ​​will be copied to _poly- but you will make an additional copy in the process. The best way to do this is to pass a const link:

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

EDIT I mentioned in the comments about copying and swapping. Another way to implement what you want is

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

, , . , . , " ", , .

+13

ints. , (_poly , poly).

, ( ).

, const:

void polynomial::Set( const vector<int>& poly )

const , .

+4

. ++. , . , .

+2

.

+2

:

void someFunction(SomeClass theObject);

void someFunction(SomeClass *theObject);

void someFunction(SomeClass &theObject);
+2

.

, , "=" .

+1

, , , . , , const.

, - , .

0

( ), . , , () . - .

- , Set() , _poly.

, :

void polynomial::Set(const vector<int>& poly) // passes the original parameter by reference
{
    _poly = poly; // still makes a copy
}
0

All Articles