8000 Clarify narrowing between = and {} · windoro/cppbestpractices@47da1a2 · GitHub
[go: up one dir, main page]

Skip to content

Commit 47da1a2

Browse files
committed
Clarify narrowing between = and {}
1 parent 2bbcaf6 commit 47da1a2

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

03-Style.md

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -257,27 +257,34 @@ private:
257257
};
258258
```
259259
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+
261264
```cpp
262265
// ... //
263266
private:
264-
int m_value = 0;
267+
int m_value = 0; // allowed
268+
unsigned m_value_2 = -1; // narrowing from signed to unsigned allowed
265269
// ... //
266270
```
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.
268276

269-
Use brace initialization; it does not allow narrowing at compile-time:
270277
```cpp
271278
// Best Idea
272279

273280
// ... //
274281
private:
275282
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
277284
// ... //
278285
```
279286
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.
281288
282289
Forgetting to initialize a member is a source of undefined behavior bugs which are often extremely hard to find.
283290

0 commit comments

Comments
 (0)
0