fork download
  1. #include <iostream>
  2. #include <new>
  3. #include <memory>
  4. #include <type_traits>
  5. using namespace std;
  6.  
  7. struct PointerHolder {
  8. PointerHolder(const void * p) {
  9. cout << "Constructed Holder @ " << this << " with p == " << p << endl;
  10. }
  11.  
  12. void * operator new(size_t, void * pp) { return pp; }
  13. const void * ptr{};
  14. };
  15.  
  16. int main() {
  17. int z{};
  18. cout << "&z == " << &z << endl;
  19.  
  20. PointerHolder p1(&z);
  21.  
  22. auto buf = aligned_storage_t<sizeof(PointerHolder), alignof(PointerHolder)>{};
  23. auto p2 = ::new (&buf) PointerHolder(&z);
  24.  
  25. // This doesn't compile
  26. // auto p3 = make_unique<PointerHolder>(&z);
  27.  
  28. // And neither does this
  29. auto p4 = new (&buf) PointerHolder(&z);
  30. return 0;
  31. }
Success #stdin #stdout 0.01s 5296KB
stdin
Standard input is empty
stdout
&z == 0x7fff350a8504
Constructed Holder @ 0x7fff350a8508 with p == 0x7fff350a8504
Constructed Holder @ 0x7fff350a8510 with p == 0x7fff350a8504
Constructed Holder @ 0x7fff350a8510 with p == 0x7fff350a8504