A mutable container of immutable objects in C ++

I would like to have something equivalent to C ++ std :: vector where the underlying objects are immutable. Therefore, I can use the push_back () functions to add them to a vector, etc. The actual std :: vector supports an array larger than the size of the vector filled with the default objects, and when you push_back (), it assigns the element to the array. My immutable objects do not have a default constructor, and assignment does not have a mutating operation, therefore, too.

I can do vector<boost::optional<T>> , but this is a dirty interface because I only want to place correctly constructed objects in the vector and deduce them from the vector.

I thought boost had something like this, but I could not find it. Does something like this exist?

+5
source share
1 answer

Your idea of ​​how vector works is wrong.

The vector uses a allocator to allocate raw memory. This raw memory does not contain objects built by default - it is just raw memory.

When you do push_back (for example), it then uses the new placement to create the object in raw memory. Similarly, when you erase an object, it will eventually call its destructor to return the object to raw memory.

With the current (C ++ 11 or later) implementation of std::vector your object should not support the default construct or purpose. Support for the movement design and movement destination should be sufficient. To use them, you would like to use emplace_back instead of push_back .

+4
source

Source: https://habr.com/ru/post/1208283/


All Articles