From f4a9420e3225fa29034a4b1c911bdb1c1e61a45c Mon Sep 17 00:00:00 2001 From: Niels Dekker Date: Thu, 13 Oct 2022 23:08:53 +0200 Subject: [PATCH] R.5 (scoped objects): Do not warn on a const `unique_ptr` (#1969) `unique_ptr` is being used in practice to declare a local dynamically allocated buffer. --- CppCoreGuidelines.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index 69fe384..2cb5bd3 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -9564,6 +9564,28 @@ Instead, use a local variable: * (Moderate) Warn if an object is allocated and then deallocated on all paths within a function. Suggest it should be a local stack object instead. * (Simple) Warn if a local `Unique_pointer` or `Shared_pointer` is not moved, copied, reassigned or `reset` before its lifetime ends. +Exception: Do not produce such a warning on a local `Unique_pointer` to an unbounded array. (See below.) + +##### Exception + +It is OK to create a local `const unique_ptr` to a heap-allocated buffer, as this is a valid way to represent a scoped dynamic array. + +##### Example + +A valid use case for a local `const unique_ptr` variable: + + int get_median_value(const std::list& integers) + { + const auto size = integers.size(); + + // OK: declaring a local unique_ptr. + const auto local_buffer = std::make_unique_for_overwrite(size); + + std::copy_n(begin(integers), size, local_buffer.get()); + std::nth_element(local_buffer.get(), local_buffer.get() + size/2, local_buffer.get() + size); + + return local_buffer[size/2]; + } ### R.6: Avoid non-`const` global variables