From 52c4376433cba034b383591662f4603f4d977626 Mon Sep 17 00:00:00 2001 From: Eliyahu Ravuna Date: Tue, 4 Oct 2016 00:42:20 +0300 Subject: [PATCH] Short string optimization example for C.180 Extra blank lines removed strcpy replaced with strcpy_s to get rid of Travis CI warnings Note: strcpy_s is defined in the Annex K of the C++11 standard. Gabriel's comments incorporated - No need for braces for a single statement. - Comment to explain why buffer_size is 16. Bracing style made consistent with the rest of the examples Bracing style made consistent with the rest of the examples braces made consistent with the rest of the examples --- CppCoreGuidelines.md | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index 22a731f..66a1604 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -7322,7 +7322,44 @@ But heed the warning: [Avoid "naked" `union`s](#Ru-naked) ##### Example - ??? short-string optimization; safe union without dscriminant ??? + // Short string optimization + + constexpr size_t buffer_size = 16; // Slightly larger than the size of a pointer + + class Immutable_string { + public: + Immutable_string(const char* str) : + size(strlen(str)) + { + if (size < buffer_size) + strcpy_s(string_buffer, buffer_size, str); + else { + string_ptr = new char[size + 1]; + strcpy_s(string_ptr, size + 1, str); + } + } + + ~Immutable_string() + { + if (size >= buffer_size) + delete string_ptr; + } + + const char* get_str() const + { + return (size < buffer_size) ? string_buffer : string_ptr; + } + + private: + // If the string is short enough, we store the string itself + // instead of a pointer to the string. + union { + char* string_ptr; + char string_buffer[buffer_size]; + }; + + const size_t size; + }; ##### Enforcement