Skip to content

Commit f894e14

Browse files
committed
Clarifying performance in POD vs other in initializer lists.
1 parent 2bbcaf6 commit f894e14

File tree

1 file changed

+33
-4
lines changed

1 file changed

+33
-4
lines changed

03-Style.md

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,9 @@ It also makes it possible to have two separate files next to each other on one s
223223
```
224224

225225
## Initialize Member Variables
226-
...with the member initializer list.
226+
...with the member initializer list.
227+
228+
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.
227229

228230
```cpp
229231
// Bad Idea
@@ -239,11 +241,23 @@ private:
239241
int m_value;
240242
};
241243

244+
// Bad Idea
245+
// This leads to an additional constructor call for m_myOtherClass
246+
// before the assignment.
247+
class MyClass
248+
{
249+
public:
250+
MyClass(MyOtherClass t_myOtherClass)
251+
{
252+
m_myOtherClass = t_myOtherClass;
253+
}
254+
255+
private:
256+
MyOtherClass m_myOtherClass;
257+
};
242258

243259
// Good Idea
244-
// C++'s member initializer list is unique to the language and leads to
245-
// cleaner code and potential performance gains that other languages cannot
246-
// match.
260+
// There is no performance gain here but the code is cleaner.
247261
class MyClass
248262
{
249263
public:
@@ -255,6 +269,21 @@ public:
255269
private:
256270
int m_value;
257271
};
272+
273+
// Good Idea
274+
// There is a performance gain here because the default constructor
275+
// for m_myOtherClass is never called.
276+
class MyClass
277+
{
278+
public:
279+
MyClass(MyOtherClass t_myOtherClass)
280+
: m_myOtherClass(t_myOtherClass)
281+
{
282+
}
283+
284+
private:
285+
MyOtherClass m_myOtherClass;
286+
};
258287
```
259288
260289
In C++11 you may consider always giving each member a default value, e.g. by writing

0 commit comments

Comments
 (0)