Immutable C++ container class

后端 未结 2 2033
走了就别回头了
走了就别回头了 2021-02-15 00:32

Say that I have a C++ class, Container, that contains some elements of type Element. For various reasons, it is inefficient, undesirable, unnecessary,

相关标签:
2条回答
  • 2021-02-15 01:06

    The STL doesn't define any lesser concepts; mostly because the idea of const is usually expressed on a per-iterator or per-reference level, not on a per-class level.

    You shouldn't provide iterator with unexpected semantics, only provide const_iterator. This allows client code to fail in the most logical place (with the most readable error message) if they make a mistake.

    Possibly the easiest way to do it would be to encapsulate it and prevent all non-const aliases.

    class example {
        std::list<sometype> stuff;
    public:
        void Process(...) { ... }
        const std::list<sometype>& Results() { return stuff; }
    };
    

    Now any client code knows exactly what they can do with the return value of Results- nada that requires mutation.

    0 讨论(0)
  • 2021-02-15 01:15

    As long as your object can provider a conforming const_iterator it doesn't have to have anything else. It should be pretty easy to implement this on your container class.

    (If applicable, look at the Boost.Iterators library; it has iterator_facade and iterator_adaptor classes to help you with the nitty-gritty details)

    0 讨论(0)
提交回复
热议问题