fork download
  1. #include <type_traits>
  2. #include <stdexcept>
  3. #include <memory>
  4. #include <iostream>
  5. struct ObjectType {
  6. int arg1, arg2;
  7. ObjectType() { std::cout << "default ctor called\n" ; } // this will NOT be printed!
  8. ObjectType(int a1, int a2) : arg1(a1), arg2(a2) {}
  9.  
  10. void* operator new[](std::size_t n, int cnt, const ObjectType& o)
  11. {
  12. if (n!=0)
  13. throw std::runtime_error("must use [0] with this new");
  14. typedef std::aligned_storage<sizeof(o), std::alignment_of<ObjectType>::value>::type buf;
  15. ObjectType* ptr = reinterpret_cast<ObjectType*>(new buf[cnt]);
  16. std::uninitialized_fill_n(ptr, cnt, o);
  17. return ptr;
  18. }
  19. };
  20.  
  21. int main()
  22. {
  23. ObjectType* object = new(100, ObjectType(1,2)) ObjectType[0]; // may not work with other classes!
  24.  
  25. std::cout << "element #0 == (" << object[0].arg1 << ", " << object[0].arg2 << ")\n";
  26. std::cout << "element #99 == (" << object[99].arg1 << ", " << object[99].arg2 << ")\n";
  27.  
  28. delete[] object; // does not call destructors for each ObjectType, needs to be implemented too.
  29. }
  30.  
  31. // tested with MSVC++ 2010 Express Edition too
Success #stdin #stdout 0s 2960KB
stdin
Standard input is empty
stdout
element #0 == (1, 2)
element #99 == (1, 2)