char operator[] (std::size_t position) {
return text[position];
}
tb[0] = ‘x’;
it is never legal to modify the return value of a function that return a built-in type.
mutable
class CTextBlock {
public:
...
std::size_t length() const;
private:
char *pText;
mutable std::size_t textLength;
mutable bool lengthIsValid;
};
std::size_t CTextBlock::length() const {
if (!lenghtIsValid) {
textLength = std::strlen(pText);
lengthIsValid = true;
}
return textLength;
}
class TextBlock {
public:
...
const char& operator[] (std::size_t position) const {
...
return text[position];
}
char& operator[] (std::size_t position) const {
return
const_cast<char&>(static_cast<const TextBlock&>(*this)[positon]);
}
};