You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 03-Style.md
+33-4Lines changed: 33 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -223,7 +223,9 @@ It also makes it possible to have two separate files next to each other on one s
223
223
```
224
224
225
225
## 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.
227
229
228
230
```cpp
229
231
// Bad Idea
@@ -239,11 +241,23 @@ private:
239
241
int m_value;
240
242
};
241
243
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
+
};
242
258
243
259
// 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.
247
261
class MyClass
248
262
{
249
263
public:
@@ -255,6 +269,21 @@ public:
255
269
private:
256
270
int m_value;
257
271
};
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
+
};
258
287
```
259
288
260
289
In C++11 you may consider always giving each member a default value, e.g. by writing
0 commit comments