|
19 | 19 | * [Memory allocation](#memory-allocation)
|
20 | 20 | * [Use `nullptr` instead of `NULL` or `0`](#use-nullptr-instead-of-null-or-0)
|
21 | 21 | * [Ownership and Smart Pointers](#ownership-and-smart-pointers)
|
| 22 | + * [Avoid non-const references](#avoid-non-const-references) |
22 | 23 | * [Others](#others)
|
23 | 24 | * [Type casting](#type-casting)
|
24 | 25 | * [Using `auto`](#using-auto)
|
@@ -212,6 +213,43 @@ ownership to the callee and invalidates the caller's instance.
|
212 | 213 |
|
213 | 214 | Don't use `std::auto_ptr`, it is deprecated ([Reference][cppref_auto_ptr]).
|
214 | 215 |
|
| 216 | +### Avoid non-const references |
| 217 | +
|
| 218 | +Using non-const references often obscures which values are changed by an |
| 219 | +assignment. Consider using a pointer instead, which requires more explicit |
| 220 | +syntax to indicate that modifications take place. |
| 221 | +
|
| 222 | +```c++ |
| 223 | +class ExampleClass { |
| 224 | + public: |
| 225 | + explicit ExampleClass(OtherClass* other_ptr) : pointer_to_other_(other_ptr) {} |
| 226 | +
|
| 227 | + void SomeMethod(const std::string& input_param, |
| 228 | + std::string* in_out_param); // Pointer instead of reference |
| 229 | +
|
| 230 | + const std::string& get_foo() const { return foo_string_; } |
| 231 | + void set_foo(const std::string& new_value) { foo_string_ = new_value; } |
| 232 | +
|
| 233 | + void ReplaceCharacterInFoo(char from, char to) { |
| 234 | + // A non-const reference is okay here, because the method name already tells |
| 235 | + // users that this modifies 'foo_string_' -- if that is not the case, |
| 236 | + // it can still be better to use an indexed for loop, or leave appropriate |
| 237 | + // comments. |
| 238 | + for (char& character : foo_string_) { |
| 239 | + if (character == from) |
| 240 | + character = to; |
| 241 | + } |
| 242 | + } |
| 243 | +
|
| 244 | + private: |
| 245 | + std::string foo_string_; |
| 246 | + // Pointer instead of reference. If this object 'owns' the other object, |
| 247 | + // this should be a `std::unique_ptr<OtherClass>`; a |
| 248 | + // `std::shared_ptr<OtherClass>` can also be a better choice. |
| 249 | + OtherClass* pointer_to_other_; |
| 250 | +}; |
| 251 | +``` |
| 252 | + |
215 | 253 | ## Others
|
216 | 254 |
|
217 | 255 | ### Type casting
|
|
0 commit comments