File tree Expand file tree Collapse file tree 1 file changed +13
-6
lines changed Expand file tree Collapse file tree 1 file changed +13
-6
lines changed Original file line number Diff line number Diff line change @@ -257,27 +257,34 @@ private:
257
257
};
258
258
```
259
259
260
- In C++11 you may consider always giving each member a default value, e.g. by writing
260
+ In C++11 you can assign default values to each member (using `=` or using `{}`).
261
+
262
+ ### Assigning default values with =
263
+
261
264
```cpp
262
265
// ... //
263
266
private:
264
- int m_value = 0;
267
+ int m_value = 0; // allowed
268
+ unsigned m_value_2 = -1; // narrowing from signed to unsigned allowed
265
269
// ... //
266
270
```
267
- inside the class body. This makes sure that no constructor ever "forgets" to initialize a member object.
271
+ This ensures that no constructor ever "forgets" to initialize a member object.
272
+
273
+ ### Assigning default values with brace initialization
274
+
275
+ Using brace initialization does not allow narrowing at compile-time.
268
276
269
- Use brace initialization; it does not allow narrowing at compile-time:
270
277
``` cpp
271
278
// Best Idea
272
279
273
280
// ... //
274
281
private:
275
282
int m_value{ 0 }; // allowed
276
- unsigned m_value_2 { -1 }; // compile-time error, narrowing from signed to unsigned.
283
+ unsigned m_value_2 { -1 }; // narrowing from signed to unsigned not allowed, leads to a compile time error
277
284
// ... //
278
285
```
279
286
280
- Prefer {} initialization over alternatives unless you have a strong reason not to.
287
+ Prefer `{}` initialization over `=` unless you have a strong reason not to.
281
288
282
289
Forgetting to initialize a member is a source of undefined behavior bugs which are often extremely hard to find.
283
290
You can’t perform that action at this time.
0 commit comments