Effective C++ 3. Use const whenever posible

来源:互联网 发布:淘宝卖家售假被扣48分 编辑:程序博客网 时间:2024/06/16 01:39
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]);    }};
原创粉丝点击