Immutable container with mutable content

后端 未结 4 1769
遇见更好的自我
遇见更好的自我 2021-01-04 15:49

The story begins with something I thought pretty simple :

I need to design a class that will use some STL containers. I need to give users of the class access to an

相关标签:
4条回答
  • 2021-01-04 15:57

    Rather than providing the user with the entire container, could you just provide them non-const iterators to beginning and end? That's the STL way.

    0 讨论(0)
  • 2021-01-04 16:02

    You need a custom data structure iterator, a wrapper around your private list.

    template<typename T>
    class inmutable_list_it {
    public:
        inmutable_list_it(std::list<T>* real_list) : real_list_(real_list) {}
    
        T first() { return *(real_list_->begin()); }
    
        // Reset Iteration
        void reset() { it_ = real_list_->begin(); }
    
        // Returns current item 
        T current() { return *it_; } 
    
        // Returns true if the iterator has a next element.
        bool hasNext(); 
    
    private:
        std::list<T>* real_list_;
        std::list<T>::iterator it_;
    };
    
    0 讨论(0)
  • 2021-01-04 16:02

    The painful solution:

    /* YOU HAVE NOT SEEN THIS */
    struct mutable_int {
        mutable_int(int v = 0) : v(v) { }
        operator int(void) const { return v; }
        mutable_int const &operator=(int nv) const { v = nv; return *this; }
    
        mutable int v;
    };
    

    Excuse me while I have to punish myself to atone for my sins.

    0 讨论(0)
  • 2021-01-04 16:05

    The simplest option would probably be a standard STL container of pointers, since const-ness is not propagated to the actual objects. One problem with this is that STL does not clean up any heap memory that you allocated. For that take a look at Boost Pointer Container Library or smart pointers.

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