Skip to content

Commit 486178b

Browse files
committed
COMP: Improve const correctness for ValueIterators
The protected deref method had inconsistent interface of being a const function that returned a non-const reference. Resolves open-source-parsers#914.
1 parent bdacfd7 commit 486178b

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

include/json/value.h

+15-4
Original file line numberDiff line numberDiff line change
@@ -772,7 +772,14 @@ class JSON_API ValueIteratorBase {
772772
char const* memberName(char const** end) const;
773773

774774
protected:
775-
Value& deref() const;
775+
/*! Internal utility functions to assist with implementing
776+
* other iterator functions. The const and non-const versions
777+
* of the "deref" protected methods expose the protected
778+
* current_ member variable in a way that can often be
779+
* optimized away by the compiler.
780+
*/
781+
const Value& deref() const;
782+
Value& deref();
776783

777784
void increment();
778785

@@ -895,9 +902,13 @@ class JSON_API ValueIterator : public ValueIteratorBase {
895902
return *this;
896903
}
897904

898-
reference operator*() const { return deref(); }
899-
900-
pointer operator->() const { return &deref(); }
905+
/*! The return value of non-const iterators can be
906+
* changed, so the these functions are not const
907+
* because the returned references/pointers can be used
908+
* to change state of the base class.
909+
*/
910+
reference operator*() { return deref(); }
911+
pointer operator->() { return &deref(); }
901912
};
902913

903914
inline void swap(Value& a, Value& b) { a.swap(b); }

src/lib_json/json_valueiterator.inl

+2-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ ValueIteratorBase::ValueIteratorBase(
2121
const Value::ObjectValues::iterator& current)
2222
: current_(current), isNull_(false) {}
2323

24-
Value& ValueIteratorBase::deref() const { return current_->second; }
24+
Value& ValueIteratorBase::deref() { return current_->second; }
25+
const Value& ValueIteratorBase::deref() const { return current_->second; }
2526

2627
void ValueIteratorBase::increment() { ++current_; }
2728

0 commit comments

Comments
 (0)