| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
1 parent da8414e commit 03803ee
1 file changed
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -16,6 +16,7 @@ | |||
| 16 | 16 | * [`nullptr` instead of `NULL` or `0`](#nullptr-instead-of-null-or-0) | |
| 17 | 17 | * [Do not include `*.h` if `*-inl.h` has already been included](#do-not-include-h-if--inlh-has-already-been-included) | |
| 18 | 18 | * [Avoid throwing JavaScript errors in nested C++ methods](#avoid-throwing-javascript-errors-in-nested-c-methods) | |
| 19 | + * [Ownership and Smart Pointers](#ownership-and-smart-pointers) | ||
| 19 | 20 | ||
| 20 | 21 | Unfortunately, the C++ linter (based on | |
| 21 | 22 | [Google’s `cpplint`](https://github.com/google/styleguide)), which can be run | |
@@ -168,3 +169,27 @@ A lot of code inside Node.js is written so that typechecking etc. is performed | |||
| 168 | 169 | in JavaScript. | |
| 169 | 170 | ||
| 170 | 171 | Using C++ `throw` is not allowed. | |
| 172 | + | ||
| 173 | + ## Ownership and Smart Pointers | ||
| 174 | + | ||
| 175 | + "Smart" pointers are classes that act like pointers, e.g. | ||
| 176 | + by overloading the `*` and `->` operators. Some smart pointer types can be | ||
| 177 | + used to automate ownership bookkeeping, to ensure these responsibilities are | ||
| 178 | + met. `std::unique_ptr` is a smart pointer type introduced in C++11, which | ||
| 179 | + expresses exclusive ownership of a dynamically allocated object; the object | ||
| 180 | + is deleted when the `std::unique_ptr` goes out of scope. It cannot be | ||
| 181 | + copied, but can be moved to represent ownership transfer. | ||
| 182 | + `std::shared_ptr` is a smart pointer type that expresses shared ownership of a | ||
| 183 | + dynamically allocated object. `std::shared_ptr`s can be copied; ownership | ||
| 184 | + of the object is shared among all copies, and the object | ||
| 185 | + is deleted when the last `std::shared_ptr` is destroyed. | ||
| 186 | + | ||
| 187 | + Prefer to use `std::unique_ptr` to make ownership | ||
| 188 | + transfer explicit. For example: | ||
| 189 | + | ||
| 190 | + ```cpp | ||
| 191 | + std::unique_ptr<Foo> FooFactory(); | ||
| 192 | + void FooConsumer(std::unique_ptr<Foo> ptr); | ||
| 193 | + ``` | ||
| 194 | + | ||
| 195 | + Never use `std::auto_ptr`. Instead, use `std::unique_ptr`. | ||
| Back | FazBrowse Home | New Git URL |
0 commit comments