From 8f2ecf0665777dc137347cee14b48b6e99a58290 Mon Sep 17 00:00:00 2001 From: hsutter Date: Mon, 30 Jan 2017 11:52:11 -0800 Subject: [PATCH] Closed #557 Added example from the issue --- CppCoreGuidelines.md | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index 2ef163b..4b0a200 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -9613,7 +9613,7 @@ not. Unfortunately, it may be impossible to detect when a non-`const` was not ##### Reason -Readability. +Readability and safety. ##### Example, bad @@ -9624,6 +9624,26 @@ Readability. for (i = 0; i < 200; ++i) { /* ... */ } // bad: i recycled } +##### Note + +As an optimization, you may want to reuse a buffer as a scratchpad, but even then prefer to limit the variables's scope as much as possible and be careful not to cause bugs from data left in a recycled buffer as this is a common source of security bugs. + + { + std::string buffer; // to avoid reallocations on every loop iteration + for (auto& o : objects) + { + // First part of the work. + generateFirstString(buffer, o); + writeToFile(buffer); + + // Second part of the work. + generateSecondString(buffer, o); + writeToFile(buffer); + + // etc... + } + } + ##### Enforcement Flag recycled variables.