fork(1) download
  1. #include <type_traits>
  2. #include <stdexcept>
  3. #include <memory>
  4. #include <iostream>
  5.  
  6. struct T {
  7. int val;
  8. T() = delete;
  9. T(int i) : val(i) {}
  10. void* operator new[](std::size_t, std::size_t cnt, const T& t)
  11. {
  12. typedef std::aligned_storage<sizeof(t),
  13. std::alignment_of<T>::value>::type buf;
  14. T* ptr = reinterpret_cast<T*>(new buf[cnt]);
  15. std::uninitialized_fill_n(ptr, cnt, t);
  16. return ptr;
  17. }
  18. };
  19.  
  20. int main()
  21. {
  22. T* a = new(100, T(7)) T[0]; // using zero is legal per 5.3.4/7
  23.  
  24. std::cout << "a[0] = " << a[0].val << '\n'
  25. << "a[1] = " << a[1].val << '\n'
  26. << "a[98] = " << a[98].val << '\n'
  27. << "a[99] = " << a[99].val << '\n';
  28. delete[] a; // I know this won't call the 100 destructors, but it will free the 100 aligned_storages at least
  29. }
  30.  
Success #stdin #stdout 0s 2960KB
stdin
Standard input is empty
stdout
a[0] = 7
a[1] = 7
a[98] = 7
a[99] = 7