Should constant contructor aguments be passed by reference or value?
- by Mike
When const values are passed to an object construct should they be passed by reference or value? If you pass by value and the arguments are immediately fed to initializes are two copies being made? Is this something that the compiler will automatically take care of. I have noticed that all textbook examples of constructors and intitializers pass by value but this seems inefficient to me.
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?