fork(7) download
  1. #include <memory>
  2. #include <cstdio>
  3.  
  4. struct MyClass {
  5. int i;
  6. MyClass(int i_) noexcept : i(i_) {}
  7. ~MyClass() { std::printf("Destroyed %d!\n", i); }
  8. };
  9.  
  10. int main() {
  11. using std::shared_ptr;
  12. using std::static_pointer_cast;
  13.  
  14. void* rawPtr = new MyClass(1);
  15. shared_ptr<void> exampleVoid(rawPtr); // Undefined behavior;
  16. // calls delete (void*)ptr;
  17.  
  18. shared_ptr<void> exampleVoidCons(new MyClass(2));
  19. // OK, calls shared_ptr<void>::shared_ptr<MyClass>(MyClass*) which
  20. // makes a deleter calling delete (MyClass*)ptr;
  21.  
  22. shared_ptr<MyClass> example(new MyClass(3)); // OK, calls delete (MyClass*)ptr;
  23.  
  24. shared_ptr<void> castToVoid = static_pointer_cast<void>(example);
  25. // OK, shared_ptr's deleter is erased so this still calls delete (MyClass*)ptr;
  26. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
Destroyed 3!
Destroyed 2!