From de702b5569c718df7bfed582973f79e1e84622fd Mon Sep 17 00:00:00 2001 From: Deukhoofd Date: Thu, 16 Apr 2020 11:01:46 +0200 Subject: [PATCH] Cleanup of ConstString. --- src/ConstString.hpp | 25 +++++++++++++++++++------ src/__ConstStringCore.hpp | 18 +++++++++--------- 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/src/ConstString.hpp b/src/ConstString.hpp index 62070c7..10d2cae 100644 --- a/src/ConstString.hpp +++ b/src/ConstString.hpp @@ -9,15 +9,28 @@ #include "__ConstStringCore.hpp" namespace Arbutils { - struct __ConstStringCharHolder { - char* Value; - std::atomic References; + class __ConstStringCharHolder { + char* _value; + std::atomic _references; - __ConstStringCharHolder(const char* value, size_t size) : Value(new char[size + 1]), References(0) { - strncpy(Value, value, size + 1); + public: + __ConstStringCharHolder(const char* value, size_t size) : _value(new char[size + 1]), _references(0) { + strncpy(_value, value, size + 1); } - ~__ConstStringCharHolder() { delete[] Value; } + ~__ConstStringCharHolder() { delete[] _value; } + + inline void RemoveReference(){ + if (--_references == 0){ + delete this; + } + } + inline void AddReference(){ + _references++; + } + inline const char* GetValue(){ + return _value; + } }; } diff --git a/src/__ConstStringCore.hpp b/src/__ConstStringCore.hpp index c28be2c..e44dc05 100644 --- a/src/__ConstStringCore.hpp +++ b/src/__ConstStringCore.hpp @@ -25,31 +25,31 @@ public: \ name(const char* str, size_t size) \ : _str(new __ConstStringCharHolder(str, size)), _length(size), _hash(Hash(str)) { \ - _str->References++; \ + _str->AddReference(); \ } \ name() : name("", 0){}; \ explicit name(const char* str) : name(str, Length(str)){}; \ explicit name(const std::string& str) : name(str.c_str(), str.size()){}; \ name(const name& other) : _str(other._str), _length(other._length), _hash(other._hash) { \ - _str->References++; \ + _str->AddReference(); \ } \ name& operator=(const name& other) { \ - if (--_str->References == 0) \ - delete _str; \ + if (_str != nullptr) \ + _str->RemoveReference(); \ _str = other._str; \ - _str->References++; \ + _str->AddReference(); \ _length = other._length; \ _hash = other._hash; \ return *this; \ } \ \ ~name() { \ - if (--_str->References == 0) \ - delete _str; \ + if (_str != nullptr) \ + _str->RemoveReference(); \ } \ \ - [[nodiscard]] inline constexpr const char* c_str() const noexcept { return _str->Value; } \ - [[nodiscard]] inline std::string std_str() const { return std::string(_str->Value, _length); } \ + [[nodiscard]] inline constexpr const char* c_str() const noexcept { return _str->GetValue(); } \ + [[nodiscard]] inline std::string std_str() const { return std::string(_str->GetValue(), _length); } \ \ [[nodiscard]] inline constexpr size_t Length() const noexcept { return _length; } \ \