Posting parts of a code on vectors. Cant understand whats going on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
9 #include <vector>
10 class A {
11 public:
12 A(); // Default constructor
13 A(int); // Non-Default Constructor
14 A(const A&); // A copy constructor is used by the compile whenever
15 A& operator=(const A&); // Assignment operator
16 ~A(); // Destructor
17 public:
18 int x; // Single data member
19 };
20
21
22 typedef std::vector<A> AVec_t; // Define a type that is vector of A’s
23 typedef std::vector<A*> APVec_t;// Define a type that is vector of A pointers

APVec_t apv0;
123
124 std::cout << "Adding an three elements to apv0"; getchar();
125 apv0.push_back(new A(2));
126 apv0.push_back(new A(10));
127 apv0.push_back(new A(100));
128 // Number of elements in a vector can be queried with "size()"
129 std::cout << "Size of apv0 is " << apv0.size() << std::endl;
130
131 // Clear the apv0 vector. Note: ~A() NOT called. Why not?
132 std::cout << "Clearing apv0"; getchar();
133 apv0.clear();
134 std::cout << "Size of apv0 is " << apv0.size() << std::endl;
135
136 std::cout << "Main program exiting"; getchar();
137 return 0;
138 }
And what your question is?

Note: ~A() NOT called. Why not?
Because apv0 is a vector of pointers. When pointer is destroyed, it does not calls destructor of pointed object:
1
2
3
{
    int* p = new int;
} //p is destroyed, but not int it points to 
Avoid raw pointers. For example unique_ptr manages memory for you.
Topic archived. No new replies allowed.