As pointed out by others, the reason for your result is the copy constructor and the vector resizing. A vector has size and capacity. Typically, capacity is usually doubled when vector needs to resize to accommodate new elements, so resizing should not occur frequently.
Adding some trace code to print the vector capacity between each push_back gives more clarity in this behavior.
m.capacity(): 0 m.capacity(): 1 m.capacity(): 2 m.capacity(): 4 m.capacity(): 4 m.capacity(): 8 Before Exiting 5 7
What actually happens here is that the only time the destructor is called is to resize the vector (see why below). The first time he resized, he has no elements, so the destructor is never called. The second time, the capacity is 1, so the destructor is called once. The third time he was called twice, and the fourth time he was called four times. This number is called seven times in the same way as the counter shows.
Elements dynamically allocated in myFunc are never freed, so the destructor never works there, and the final printout ("Before exiting ...") is performed before leaving the area where vector is selected, therefore the destructor for the last "vector reincarnation "is not called only after this listing. Therefore, the MyClass destructor is called only when the vector is resized.
source share