Skip to content

Commit a7100e2

Browse files
committed
added constness_ptr as pointer wrapper to ensure actual method constness
1 parent a766d22 commit a7100e2

File tree

2 files changed

+64
-5
lines changed

2 files changed

+64
-5
lines changed

simplecpp.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -540,7 +540,7 @@ void simplecpp::TokenList::clear()
540540
backToken = nullptr;
541541
while (frontToken) {
542542
Token * const next = frontToken->next;
543-
delete frontToken;
543+
delete frontToken.get();
544544
frontToken = next;
545545
}
546546
sizeOfType.clear();

simplecpp.h

Lines changed: 63 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,65 @@ namespace simplecpp {
7171
class Macro;
7272
class FileDataCache;
7373

74+
// as std::optional behaves similarly we could use that instead if we ever move to C++17.
75+
// it is not a simple drop-in as our "operator bool()" indicates if the pointer is non-null
76+
// whereas std::optional indicates if a value is set.
77+
//
78+
// This is similar to std::experimental::propagate_const
79+
// see https://en.cppreference.com/w/cpp/experimental/propagate_const
80+
template<typename T>
81+
class constness_ptr
82+
{
83+
public:
84+
explicit constness_ptr(T* p)
85+
: mPtr(p)
86+
{}
87+
88+
constness_ptr<T> &operator=(T* p) {
89+
mPtr = p;
90+
return *this;
91+
}
92+
93+
T* get() noexcept {
94+
return mPtr;
95+
}
96+
97+
const T* get() const noexcept {
98+
return mPtr;
99+
}
100+
101+
operator T*() noexcept {
102+
return mPtr;
103+
}
104+
105+
operator const T*() const noexcept {
106+
return mPtr;
107+
}
108+
109+
T* operator->() noexcept {
110+
return mPtr;
111+
}
112+
113+
const T* operator->() const noexcept {
114+
return mPtr;
115+
}
116+
117+
T& operator*() noexcept {
118+
return *mPtr;
119+
}
120+
121+
const T& operator*() const noexcept {
122+
return *mPtr;
123+
}
124+
125+
explicit operator bool() const noexcept {
126+
return mPtr != nullptr;
127+
}
128+
129+
private:
130+
T* mPtr;
131+
};
132+
74133
/**
75134
* Location in source code
76135
*/
@@ -155,8 +214,8 @@ namespace simplecpp {
155214
bool number;
156215
bool whitespaceahead;
157216
Location location;
158-
Token *previous{};
159-
Token *next{};
217+
constness_ptr<Token> previous;
218+
constness_ptr<Token> next;
160219
mutable const Token *nextcond{};
161220

162221
const Token *previousSkipComments() const {
@@ -364,8 +423,8 @@ namespace simplecpp {
364423

365424
unsigned int fileIndex(const std::string &filename);
366425

367-
Token *frontToken;
368-
Token *backToken;
426+
constness_ptr<Token> frontToken;
427+
constness_ptr<Token> backToken;
369428
std::vector<std::string> &files;
370429
};
371430

0 commit comments

Comments
 (0)