Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ equivalent to an immutable container

A recent discussion led me to the question:

Do immutable containers exist in C++? Alternately, since C++ prefers iterators to generalized containers, do immutable iterators exist?

I'm talking about something like the equivalent of Guava's ImmutableList or the built-in Collections.unmodifiable* methods. To be clear, those two types of collections are very different - the former is inherently immutable, while the latter is only immutable by actors who get the unmodifiable reference, but is potentially modifiable by actors who have access to the unwrapped object.

I'm interested to know if there is a standardized (actual or de-facto, as in Guava) equivalent to ImmutableCollection:

  • A collection which can never be modified, by any actor. Additionally, functions which take this type are providing documentation that they cannot and will not modify such collections received as arguments, or returned as return values.

or to ret ro = Colletions.unmodifiableCollection(orginalCollection) (and related methods):

  • Subtly different than the above, this is a view of the original collection, which is modifiable by anyone who has the originalCollection but not by anyone with the return value ro. Usually it is implemented by wrapping the original collection in a proxy that prevents any modification, but other implementations are possible.

I'm well aware of const std::iterator and friends, but this is very different - it ensures that the a caller can pass an object to a callee, and the object won't modify it, but it does not guarantee to the callee that the object won't be modified.

Now I'm a long-time C++ user here, although admittedly not in the last 5 years, and I couldn't come up with the obvious equivalent.

like image 453
BeeOnRope Avatar asked Feb 20 '16 03:02

BeeOnRope


1 Answers

There's a project called immer which might be able to handle this this need:

"immutable and persistent data structures for C++"

https://github.com/arximboldi/immer

like image 182
Catskul Avatar answered Sep 23 '22 07:09

Catskul