mirror of
https://github.com/isocpp/CppCoreGuidelines.git
synced 2024-03-22 13:30:58 +08:00
Merge pull request #758 from Eliyahu-Ravuna/patch-22
Short string optimization example for C.180
This commit is contained in:
commit
804964d653
|
@ -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
|
||||
|
||||
|
|
Loading…
Reference in New Issue
Block a user