My class (let's call it A
) takes in a string::iterator
and it implements two methods:
auto peek() const -> const char &
: Returns a reference to the data at the current position.auto get() -> const char &
: Returns a reference to the data at the current position then increments the position.
The solution I have come up with is the following:
class A {
std::string::iterator _s;
public:
A() = delete;
explicit A(std::string::iterator s) : _s(s) {}
auto peek() const -> const char & {
return *_s;
}
auto get() -> const char & {
return *(_s++); // <-- valid?
}
};
In this case, I understand returning a temporary copy of the value would also work since char
is small enough in size:
auto get2() -> char {
const auto c = *_s;
_s++;
return c;
}
However, say the data was sufficiently large enough such that I wanted to return a reference instead of copying. Would the following code be a valid way of doing this in C++?
auto get() -> const char & {
return *(_s++);
}