fork(1) download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. using namespace std;
  5.  
  6. struct MyClass
  7. {
  8. MyClass() { cout << "MyClass ctor runned." << endl; }
  9. ~MyClass() { cout << "MyClass dtor runned." << endl; }
  10. };
  11.  
  12. int main()
  13. {
  14. unique_ptr<MyClass> up1(new MyClass);
  15. up1 = make_unique<MyClass>(); // since C++14
  16.  
  17. {
  18. cout << "Entered inner block." << endl;
  19. unique_ptr<MyClass> up2(new MyClass);
  20.  
  21. //up1 = up2; // Syntax error
  22. up1 = move(up2); // Ownership moved from up2 to up1
  23. up2.reset(); // No memory deallocation
  24. cout << "Leaving inner block." << endl;
  25. }
  26. cout << "Left inner block." << endl;
  27.  
  28. up1.reset(); // Memory deallocation
  29. cout << "Leaving main() function." << endl;
  30.  
  31. return 0;
  32. }
Success #stdin #stdout 0s 5428KB
stdin
Standard input is empty
stdout
MyClass ctor runned.
MyClass ctor runned.
MyClass dtor runned.
Entered inner block.
MyClass ctor runned.
MyClass dtor runned.
Leaving inner block.
Left inner block.
MyClass dtor runned.
Leaving main() function.