Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Updated exception numbering; NFC

...

Code Block
bgColor#ccccff
langcpp
#include <memory>

template <typename T, typename Alloc = std::allocator<T>>
class Container {
  T *UnderlyingStorage;
  size_t NumElements;
  
  void CopyElements(T *From, T *To, size_t Count);
  
public:
  void reserve(size_t Count) {
    if (Count > NumElements) {
      Alloc A;
      T *P = A.allocate(Count); // Throws on failure
      try {
        CopyElements(UnderlyingStorage, P, NumElements);
        for (size_t i = NumElements; i < Count; ++i) {
          A.construct(&P[i]);
        }
      } catch (...) {
        A.deallocate(P, Count);
        throw;
      }
      UnderlyingStorage = P;
    }
    NumElements = Count;
  }
  
  T &operator[](size_t Idx) { return UnderlyingStorage[Idx]; }
  const T &operator[](size_t Idx) const { return UnderlyingStorage[Idx]; }
};

Exceptions

MEM33MEM53-CPP-EX1: If the object is trivially constructable, it need not have its constructor explicitly called to initiate the object's lifetime. If the object is trivially destructible, it need not have its destructor explicitly called to terminate the object's lifetime. These properties can be tested by calling std::is_trivially_constructible() and std::is_trivially_destructible() from <type_traits>. For instance, integral types such as int and long long do not require an explicit constructor or destructor call.

...