0

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)
a06e
  • 18,594
  • 33
  • 93
  • 169
  • @LukasRieger Yes that is what I want. But I also want to define some `operators` on it, so I have to implement my own class. My question is about how I should implement my class. – a06e Aug 16 '15 at 22:10

1 Answers1

1

Do declare move assignement and swap as noexcept. But don't throw on mismatched sizes...

Since your arrays are fixed-size, ending up assigning or swapping two arrays of different sizes can't possibly work, in any circumstances. It's not an exceptional condition, it's a situation where the program doesn't know what it's doing. That's a case for an assertion.

Quentin
  • 62,093
  • 7
  • 131
  • 191