0

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?

Marco Agnese
  • 349
  • 4
  • 15

3 Answers3

2

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
cadaniluk
  • 15,027
  • 2
  • 39
  • 67
  • 3
    This is technically true. However, the reference will probably be compiled to a pointer, which means that the *pointer* has to be copied instead of the value. – Jørgen Fogh Nov 04 '15 at 16:58
1

Basically, constructor 2 will make a copy twice: first time on call and the second time on intialization. On the other hand, you understand that reference is nothing more than a pointer and as the size of referenced variable decreases to pointer size there is no cost reduction between contsructors 1 and 2.

Sergey Kanaev
  • 570
  • 5
  • 18
1

In general, you never need to pass int variables by const reference.

The real question is: Why do you care? There will only be a measurable speed difference if Foo is constructed inside a loop with very many iterations and it is pretty much the only thing which happens inside that loop - very unlikely.

So just use #2. Not because of efficiency but because it is simpler.

Jørgen Fogh
  • 7,516
  • 2
  • 36
  • 46
  • int was only for seek of simplicity. Use a templated argument instead of int. My question was about the number of copy if no copy-elision is performed by the compiler – Marco Agnese Nov 04 '15 at 17:00