From f894e14e122f5569e954904018d9e9eede268801 Mon Sep 17 00:00:00 2001 From: Olivia Date: Wed, 31 May 2017 01:53:14 +0200 Subject: [PATCH] Clarifying performance in POD vs other in initializer lists. --- 03-Style.md | 37 +++++++++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/03-Style.md b/03-Style.md index 6d827dc..123406f 100644 --- a/03-Style.md +++ b/03-Style.md @@ -223,7 +223,9 @@ It also makes it possible to have two separate files next to each other on one s ``` ## Initialize Member Variables -...with the member initializer list. +...with the member initializer list. + +For POD types, the performance of an initializer list is the same as manual initialization, but for other types there is a clear performance gain, see below. ```cpp // Bad Idea @@ -239,11 +241,23 @@ private: int m_value; }; +// Bad Idea +// This leads to an additional constructor call for m_myOtherClass +// before the assignment. +class MyClass +{ +public: + MyClass(MyOtherClass t_myOtherClass) + { + m_myOtherClass = t_myOtherClass; + } + +private: + MyOtherClass m_myOtherClass; +}; // Good Idea -// C++'s member initializer list is unique to the language and leads to -// cleaner code and potential performance gains that other languages cannot -// match. +// There is no performance gain here but the code is cleaner. class MyClass { public: @@ -255,6 +269,21 @@ public: private: int m_value; }; + +// Good Idea +// There is a performance gain here because the default constructor +// for m_myOtherClass is never called. +class MyClass +{ +public: + MyClass(MyOtherClass t_myOtherClass) + : m_myOtherClass(t_myOtherClass) + { + } + +private: + MyOtherClass m_myOtherClass; +}; ``` In C++11 you may consider always giving each member a default value, e.g. by writing