fork(1) download
  1. #include <iostream>
  2.  
  3. //===========================================
  4. #define new static_assert(false, "'new' is not available");
  5.  
  6. #pragma push_macro("new")
  7. #undef new
  8.  
  9. template<typename Type, typename ...Args>
  10. void priv_PlacementNew(Type *ptr, Args&& ...args)
  11. {
  12. new (ptr) Type(std::forward<Args>(args)...);
  13. }
  14.  
  15. #pragma pop_macro("new")
  16. //===========================================
  17.  
  18. class MyClass
  19. {
  20. public:
  21. MyClass(int value) : value(value) { }
  22.  
  23.  
  24. void Print() { std::cout << "Print() = " << value << std::endl; }
  25.  
  26. private:
  27. int value = 0;
  28. };
  29.  
  30. int main()
  31. {
  32. unsigned char *bytes = (unsigned char*)malloc(sizeof(MyClass));
  33. MyClass *myClass = reinterpret_cast<MyClass*>(bytes);
  34.  
  35. //new (myClass) Type(357); //<<<---------- FAILS TO COMPILE (as desired)
  36.  
  37. priv_PlacementNew(myClass, 357);
  38.  
  39. myClass->Print();
  40.  
  41. myClass->~MyClass();
  42. free(bytes);
  43.  
  44. return 0;
  45. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
Print() = 357