From f30fcdb00201281a2b4045d0cd38e36262d3cbea Mon Sep 17 00:00:00 2001 From: Franziska Hinkelmann Date: Wed, 15 Nov 2017 19:01:23 +0100 Subject: [PATCH] doc: mention smart pointers in Cpp style guide Add rule for smart pointers, i.e., std::unique_ptr and std::shared_ptr, to the Cpp style guide. Mostly copied from the Google style guide. PR-URL: https://github.com/nodejs/node/pull/17055 Ref: https://github.com/nodejs/node/pull/16970 Ref: https://github.com/nodejs/node/pull/16974 Ref: https://github.com/nodejs/node/pull/17000 Ref: https://github.com/nodejs/node/pull/17012 Ref: https://github.com/nodejs/node/pull/17020 Ref: https://github.com/nodejs/node/pull/17030 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig --- CPP_STYLE_GUIDE.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/CPP_STYLE_GUIDE.md b/CPP_STYLE_GUIDE.md index 3c552fc2bf2a16..1dad8592f9694c 100644 --- a/CPP_STYLE_GUIDE.md +++ b/CPP_STYLE_GUIDE.md @@ -16,6 +16,7 @@ * [`nullptr` instead of `NULL` or `0`](#nullptr-instead-of-null-or-0) * [Do not include `*.h` if `*-inl.h` has already been included](#do-not-include-h-if--inlh-has-already-been-included) * [Avoid throwing JavaScript errors in nested C++ methods](#avoid-throwing-javascript-errors-in-nested-c-methods) +* [Ownership and Smart Pointers](#ownership-and-smart-pointers) Unfortunately, the C++ linter (based on [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 in JavaScript. Using C++ `throw` is not allowed. + +## Ownership and Smart Pointers + +"Smart" pointers are classes that act like pointers, e.g. +by overloading the `*` and `->` operators. Some smart pointer types can be +used to automate ownership bookkeeping, to ensure these responsibilities are +met. `std::unique_ptr` is a smart pointer type introduced in C++11, which +expresses exclusive ownership of a dynamically allocated object; the object +is deleted when the `std::unique_ptr` goes out of scope. It cannot be +copied, but can be moved to represent ownership transfer. +`std::shared_ptr` is a smart pointer type that expresses shared ownership of a +dynamically allocated object. `std::shared_ptr`s can be copied; ownership +of the object is shared among all copies, and the object +is deleted when the last `std::shared_ptr` is destroyed. + +Prefer to use `std::unique_ptr` to make ownership +transfer explicit. For example: + +```cpp +std::unique_ptr FooFactory(); +void FooConsumer(std::unique_ptr ptr); +``` + +Never use `std::auto_ptr`. Instead, use `std::unique_ptr`.