c++constructorpass-by-valuepass-by-const-reference

Argument passed by value or const reference in the constructor


Which constructor is better for the following class?

struct Foo
{ 
  Foo(const int& val):val_(val){} // constructor 1    
  Foo(int val):val_(val){} // constructor 2
  int val_;
};

Without any compiler optimization, do they copy val only once or does constructor 2 create a further copy before the initialization list?


Solution

  • If the first constructor is called, the argument passed to it will not be copied. The val argument will bind to the argument passed (copy by reference).

    If the second constructor is called, the argument passed to it will be copied by value.

    Both constructors are the same in that they initialize _val with val respectively and perform an additional copy by value.

    So, without any optimizations, it looks like this:

                                                        Copies
    const int& constructor          1
    int constructor                          2