fork download
  1. #include <iostream>
  2. #include <memory>
  3. using namespace std;
  4.  
  5. class Test {
  6. int n;
  7. public:
  8. Test(int n) : n{n} { cout<<"Constructor"<<n<<endl; }
  9. void show() { cout <<"Do something"<<n<<endl; }
  10. ~Test() { cout << "Destructor"<<n<<endl; }
  11. };
  12.  
  13. class TestDeleterWrong {
  14. public:
  15. void operator()(Test* x) {
  16. x->show();
  17. }
  18. };
  19. class TestDeleterRight {
  20. public:
  21. void operator()(Test* x) {
  22. x->show();
  23. delete x;
  24. }
  25. };
  26.  
  27. int main() {
  28. {
  29. auto p = make_unique<Test>(1); //ok
  30. }
  31. {
  32. auto p = unique_ptr<Test>(new Test(2)); //ok
  33. }
  34. {
  35. auto p = unique_ptr<Test, TestDeleterWrong>(new Test(3)); // no
  36. }
  37. {
  38. auto p = unique_ptr<Test, TestDeleterRight>(new Test(4)); // ok
  39. }
  40. return 0;
  41. }
Success #stdin #stdout 0s 4272KB
stdin
Standard input is empty
stdout
Constructor1
Destructor1
Constructor2
Destructor2
Constructor3
Do something3
Constructor4
Do something4
Destructor4