fork download
  1. #include <array>
  2. #include <iostream>
  3. #include <memory>
  4.  
  5. const size_t N = 5;
  6.  
  7. struct A
  8. {
  9. int x;
  10. A(int x) : x(x) { std::cout << "Created" << std::endl; }
  11. A(const A& rhs) : x(rhs.x) { std::cout << "Copied" << std::endl; }
  12. ~A() { std::cout << "Destroyed" << std::endl; }
  13. };
  14.  
  15. int makeElement(size_t i)
  16. {
  17. return i * i;
  18. }
  19.  
  20. struct Deleter
  21. {
  22. Deleter() {};
  23. void operator()(std::array<A, N>* p) const
  24. {
  25. for (auto& item : *p) { item.~A(); }
  26. std::return_temporary_buffer(p);
  27. };
  28. };
  29.  
  30. std::unique_ptr<std::array<A, N>, Deleter> makeArrayDynamically()
  31. {
  32. A* buf;
  33. std::tie(buf, std::ignore) = std::get_temporary_buffer<A>(N);
  34. for (size_t i = 0; i < N; ++i)
  35. {
  36. new (buf + i) A(makeElement(i)); // Yeah, I will have a leak if some constructor throws
  37. }
  38. return { reinterpret_cast<std::array<A, N>*>(buf), Deleter() };
  39. }
  40.  
  41. int main()
  42. {
  43. const auto pArr = makeArrayDynamically();
  44.  
  45. for (const auto& item : *pArr)
  46. {
  47. std::cout << item.x << std::endl;
  48. }
  49. }
  50.  
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
Created
Created
Created
Created
Created
0
1
4
9
16
Destroyed
Destroyed
Destroyed
Destroyed
Destroyed