Should constant contructor aguments be passed by reference or value?

Posted by Mike on Stack Overflow See other posts from Stack Overflow or by Mike
Published on 2011-01-07T23:44:48Z Indexed on 2011/01/07 23:53 UTC
Read the original article Hit count: 195

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?

© Stack Overflow or respective owner

Related posts about c++

Related posts about constructor