Skip to content

Commit ad3611d

Browse files
committed
Merge pull request #39 from vladon/patch-2
Update 04-Considering_Safety.md
2 parents 2f5e538 + f6b955a commit ad3611d

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

04-Considering_Safety.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,52 @@ You don't want to have to pay a cost for copying the data when you don't need to
4949
5050
See also this discussion for more information: https://github.com/lefticus/cppbestpractices/issues/21
5151
52+
### Do not pass and return simple types by const ref
53+
54+
```cpp
55+
// Very Bad Idea
56+
class MyClass
57+
{
58+
public:
59+
explicit MyClass(const int& t_int_value)
60+
: m_int_value(t_int_value)
61+
{
62+
}
63+
64+
const int& get_int_value() const
65+
{
66+
return m_int_value;
67+
}
68+
69+
private:
70+
int m_int_value;
71+
}
72+
```
73+
74+
Instead, pass and return simple types by value. If you plan not to change passed value, declare them as `const`, but not `const` refs:
75+
76+
```cpp
77+
// Good Idea
78+
class MyClass
79+
{
80+
public:
81+
explicit MyClass(const int t_int_value)
82+
: m_int_value(t_int_value)
83+
{
84+
}
85+
86+
int get_int_value() const
87+
{
88+
return m_int_value;
89+
}
90+
91+
private:
92+
int m_int_value;
93+
}
94+
```
95+
96+
Why? Because passing and returning by reference leads to pointer operations instead by much more faster passing values in processor registers.
97+
5298
## Avoid Raw Memory Access
5399
54100
Raw memory access, allocation and deallocation, are difficult to get correct in C++ without [risking memory errors and leaks](http://blog2.emptycrate.com/content/nobody-understands-c-part-6-are-you-still-using-pointers). C++11 provides tools to avoid these problems.

0 commit comments

Comments
 (0)