Search code examples
c++performancemember-initializationctor-initializer

Is there a performance difference between member initializer lists and assignment?


I was recently discussing with a friend and they said there is a performance gain when you use an initialization list to (as opposed to not and simply assigning the data members) when creating objects in C++.

Why is this (if it is true)?

I found this page:

http://www.parashift.com/c++-faq/init-lists.html

and they mention temporary objects but I would have thought recent compilers could avoid this?


Solution

  • When using assignment, the objects are default constructed before you get to the assignment. If constructing and copying an object are expensive operations, you should at least get rid of one of them. An initialization list gets rid of the additional copying operation. Copy constructing allows to do both at the same time.