From 3e4736712af36f6c3e272ec1aaee6d5b4ddb33d0 Mon Sep 17 00:00:00 2001 From: Jason Turner Date: Tue, 2 Jun 2015 08:13:09 -0600 Subject: [PATCH] Additional notes about shared and unique_ptr --- 07-Considering_Performance.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/07-Considering_Performance.md b/07-Considering_Performance.md index d2eb343..7dcf212 100644 --- a/07-Considering_Performance.md +++ b/07-Considering_Performance.md @@ -207,12 +207,20 @@ std::make_shared(); // (it's also more readable and concise) ### Prefer `unique_ptr` to `shared_ptr` -If possible use `unique_ptr` instead of `shared_ptr`. The `unique_ptr` does not need to keep track of its copies because it is not copyable. Because of this it is more efficient than the `shared_ptr`. Equivalent to `shared_ptr` and `make_shared` you should use `make_unique` to create the `unique_ptr`: +If possible use `unique_ptr` instead of `shared_ptr`. The `unique_ptr` does not need to keep track of its copies because it is not copyable. Because of this it is more efficient than the `shared_ptr`. Equivalent to `shared_ptr` and `make_shared` you should use `make_unique` (C++14 or greater) to create the `unique_ptr`: ```cpp std::make_unique(); ``` +Current best practices suggest returning a `unique_ptr` from factory functions as well, then converting the `unique_ptr` to a `shared_ptr` if necessary. + +```cpp +std::unique_ptr factory(); + +auto shared = std::shared_ptr(factory()); +``` + ### Get rid of std::endl `std::endl` implies a flush operation. It's equivalent to `"\n" << std::flush`.