fork download
  1. #include <iostream>
  2. #include <new> // For placement new
  3.  
  4. // Example class
  5. class MyClass {
  6. public:
  7. MyClass() { std::cout << "Constructor called." << std::endl; }
  8. ~MyClass() { std::cout << "Destructor called." << std::endl; }
  9. };
  10.  
  11. int main() {
  12. std::cout << "Example 1: Explicit Destructor Call" << std::endl;
  13. {
  14. MyClass obj;
  15. obj.~MyClass(); // Explicitly calling the destructor
  16. std::cout << "End of scope. Destructor will be called again." << std::endl;
  17. } // Destructor will be called again here
  18.  
  19. std::cout << "\nExample 2: Placement New with Explicit Destructor Call" << std::endl;
  20. {
  21. char buffer[sizeof(MyClass)];
  22. MyClass* obj = new (buffer) MyClass(); // Placement new
  23. obj->~MyClass(); // Explicitly calling the destructor
  24. std::cout << "End of scope. No additional destructor call." << std::endl;
  25. }
  26.  
  27. return 0;
  28. }
  29.  
Success #stdin #stdout 0.01s 5320KB
stdin
10
aba
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
stdout
Example 1: Explicit Destructor Call
Constructor called.
Destructor called.
End of scope. Destructor will be called again.
Destructor called.

Example 2: Placement New with Explicit Destructor Call
Constructor called.
Destructor called.
End of scope. No additional destructor call.