diff --git a/simplecpp.cpp b/simplecpp.cpp index 8f1879ef..8511c84f 100644 --- a/simplecpp.cpp +++ b/simplecpp.cpp @@ -540,7 +540,7 @@ void simplecpp::TokenList::clear() backToken = nullptr; while (frontToken) { Token * const next = frontToken->next; - delete frontToken; + delete frontToken.get(); frontToken = next; } sizeOfType.clear(); @@ -1354,7 +1354,6 @@ void simplecpp::TokenList::constFoldLogicalOp(Token *tok) void simplecpp::TokenList::constFoldQuestionOp(Token **tok1) { bool gotoTok1 = false; - // NOLINTNEXTLINE(misc-const-correctness) - technically correct but used to access non-const data for (Token *tok = *tok1; tok && tok->op != ')'; tok = gotoTok1 ? *tok1 : tok->next) { gotoTok1 = false; if (tok->str() != "?") @@ -1950,7 +1949,6 @@ namespace simplecpp { } } - // NOLINTNEXTLINE(misc-const-correctness) - technically correct but used to access non-const data Token * const output_end_1 = output.back(); const Token *valueToken2; diff --git a/simplecpp.h b/simplecpp.h index e164fa90..d7fc0a81 100644 --- a/simplecpp.h +++ b/simplecpp.h @@ -71,6 +71,68 @@ namespace simplecpp { class Macro; class FileDataCache; + // as std::optional behaves similarly we could use that instead if we ever move to C++17. + // it is not a simple drop-in as our "operator bool()" indicates if the pointer is non-null + // whereas std::optional indicates if a value is set. + // + // This is similar to std::experimental::propagate_const + // see https://en.cppreference.com/w/cpp/experimental/propagate_const + template + class constness_ptr + { + public: +#ifndef _MSC_VER + explicit +#endif + constness_ptr(T* p) + : mPtr(p) + {} + + constness_ptr &operator=(T* p) { + mPtr = p; + return *this; + } + + T* get() noexcept { + return mPtr; + } + + const T* get() const noexcept { + return mPtr; + } + + operator T*() noexcept { + return mPtr; + } + + operator const T*() const noexcept { + return mPtr; + } + + T* operator->() noexcept { + return mPtr; + } + + const T* operator->() const noexcept { + return mPtr; + } + + T& operator*() noexcept { + return *mPtr; + } + + const T& operator*() const noexcept { + return *mPtr; + } + + explicit operator bool() const noexcept { + return mPtr != nullptr; + } + + private: + T* mPtr; + }; + /** * Location in source code */ @@ -155,8 +217,8 @@ namespace simplecpp { bool number; bool whitespaceahead; Location location; - Token *previous{}; - Token *next{}; + constness_ptr previous; + constness_ptr next; mutable const Token *nextcond{}; const Token *previousSkipComments() const { @@ -364,8 +426,8 @@ namespace simplecpp { unsigned int fileIndex(const std::string &filename); - Token *frontToken; - Token *backToken; + constness_ptr frontToken; + constness_ptr backToken; std::vector &files; };