Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable container with mutable content

Tags:

c++

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 immutable version of those containers. I do not want users to be able to change the container (they can not push_back() on a list for instance), but I want users to be able to change the contained objects (get an element with back() and modify it) :

class Foo
{
    public:

    // [...]

    ImmutableListWithMutableElementsType getImmutableListWithMutableElements();

    // [...]
};

// [...]

myList = foo.getImmutableListWithMutableElements();
myElement = myList.back();
myElement.change(42); // OK

// [...]

// myList.push_back(myOtherElement); // Not possible

At first glance, it seems that a const container will do. But of course, you can only use a const iterator on a const container and you can not change the content.

At second glance, things like specialized container or iterator come to mind. I will probably end up with that.

Then, my thought is "Someone must have done that already !" or "An elegant, generic solution must exist !" and I'm here asking my first question on SO :

How do you design / transform a standard container into an immutable container with mutable content ?

I'm working on it but I feel like someone will just say "Hey, I do that every time, it's easy, look !", so I ask...

Thank you for any hints, suggestions or wonderful generic ways to do that :)


EDIT:

After some experiments, I ended up with standard containers that handle some specifically decorated smart pointers. It is close to Nikolai answer.

The idea of an immutable container of mutable elements is not a killing concept, see the interesting notes in Oli answer.

The idea of a specific iterator is right of course, but it seems not practical as I need to adapt to any sort of container.

Thanks to you all for your help.

like image 627
neuro Avatar asked Jan 25 '11 18:01

neuro


People also ask

Which Python containers are immutable?

Mutable and Immutable Data Types in Python. Some of the mutable data types in Python are list, dictionary, set and user-defined classes. On the other hand, some of the immutable data types are int, float, decimal, bool, string, tuple, and range.

What is a mutable container?

A mutable container is one whose contents can be changed after it is created. A non mutable container is one whose contents are fixed.


1 Answers

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.

like image 161
Nikolai Fetissov Avatar answered Sep 22 '22 20:09

Nikolai Fetissov