When const values are passed to an object's constructor should they be passed by reference or value?
All textbook examples of constructors and initializers pass by value, but this seems inefficient to me.If you pass by value and the arguments are immediately used to initialize a member variable, are two copies being made? Is this something that the compiler will automatically take care of?
class Point {
public:
int x;
int y;
Point(const int _开发者_开发问答x, const int _y) : x(_x), y(_y) {}
};
int main() {
const int a = 1, b = 2;
Point p(a,b);
Point q(3,5);
cout << p.x << "," << p.y << endl;
cout << q.x << "," << q.y << endl;
}
vs.
class Point {
public:
int x;
int y;
Point(const int& _x, const int& _y) : x(_x), y(_y) {}
};
Both compile and do the same thing, but which is correct?
For simple types passing by value is fine, you are just copying a few bytes of data. But for more complicated types like vectors and strings it's better to pass a const reference. Copying a large string or vector is a waste if you don't need a copy of it.
You are choosing here between passing a reference and passing a value. Note that these function signatures are identical.
Point( int x, int y );
Point( const int x, const int y );
From a callers point of view it doesn't matter whether the parameter is modified or not as a copy is always made when parameters are passed by value.
You need to pass a reference if you want to initialize a reference or pointer to that actual object outside the constructor, if you only need its value then passing by value is usually preferable unless the cost of copying the object is too expensive. For int
this is never the case.
It is probably preferable to pass a small primitive type like int
by value rather than by reference. If I recall correctly, references are implemented behind the scenes as hidden pointers (i.e. pass in the address and automatically de-reference it). That would mean you still incur the overhead of copying the and de-referencing the pointer (same size as an int
on some architectures).
Passing by reference-to-const
definitely makes more sense for larger user-defined types, as it saves you a potentially expensive copy operation.
Something simple like an int should be passed by value.
If you have a large object then passing by reference would make sense as it avoids making an unnecessary copy.
Note that if your object is mutable then there is a semantic difference between passing a reference or a copy - in the former case you will see the changes to the original, and in the latter case you won't. This is true even if you have declared it as a reference to const.
精彩评论