fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <memory> // For std::unique_ptr and std::make_unique
  4.  
  5. struct MyType {
  6. int a;
  7. MyType(int x) : a(x) {
  8. std::cout << "MyType constructor called with a: " << a << std::endl;
  9. }
  10. ~MyType() {
  11. std::cout << "MyType destructor called " << a << std::endl;
  12. }
  13. };
  14.  
  15. int main() {
  16. // Create a vector of unique_ptr to MyType
  17. std::vector<std::unique_ptr<MyType>> myVector;
  18.  
  19. // Insert elements using std::make_unique
  20. for (int i = 0; i < 3; ++i) {
  21. myVector.push_back(std::make_unique<MyType>(i + 1));
  22. }
  23. std::cout << "Calling clear()..." << std::endl;
  24. myVector.clear();
  25. return 0;
  26. }
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
MyType constructor called with a: 1
MyType constructor called with a: 2
MyType constructor called with a: 3
Calling clear()...
MyType destructor called 1
MyType destructor called 2
MyType destructor called 3