The problem with std::array
is that it has a fixed compile-time size. I want a container that can be created with a dynamic size, but that size stays fixed throughout the life of the container (so std::vector
won't work, because push_back
will increment the size by 1).
I am wondering how to implement this. I tried writing a class that contains an internal std::vector
for storage, and only exposes the members of std::vector
that don't change the size. My question is regarding the copy/move assignment operators, as well as the swap
member function. Usually, move assignment is declared as noexcept
. However, before assignment, I have to check if the lhs
and the rhs
are of the same size. If they are not, I must throw an exception, because otherwise, assigning rhs
to lhs
would change the size of lhs
, which I don't want. The same happens with swap
, which in my implementation is noexcept
for the same reason.
I know I am going against usual advice to make swap
and move assignment noexcept
(Item 14 of Scott Meyers' Modern Effective C++), so I am wondering if this is good design? Or is there a better way to implement a fixed runtime size container?
Example: Suppose I have defined my fixed size container with the name FixedSizeArray<T>
.
auto arr1 = FixedSizeArray<double>(4, 1.0)
The last line of code defined a FixedSizeArray
containing doubles of size 4. Now define another:
auto arr2 = FixedSizeArray<double>(10, 1.0)
Should the following line:
arr1 = std::move(arr2)
throw? What about:
arr1.swap(arr2)