std::vector calling destructor multiple times during push_back?

前端 未结 1 1345
半阙折子戏
半阙折子戏 2020-12-10 08:43

I\'m pushing objects class tipo to a vector, when I push the first one the constructor get\'s called (as it should) and the destructor is called immediatelly (which I don\'t

1条回答
  •  独厮守ぢ
    2020-12-10 09:15

    Each line of your code creates a temporary Item, copies it into the vector's memory, and then destroys the temporary. That's why you see (at least) one destructor call each time.

    In C++11, you could avoid creating and destroying the temporary by using emplace_back(args...) rather than push_back(Item(args...)), to create the object directly in the vector's memory.

    Additionally, the vector sometimes needs to grow, reallocating a larger block of memory, in order to keep all its elements in a contiguous array. When it does that, each element is moved into the new memory, and the old elements are destroyed. That's why you sometimes see more than one destructor call.

    You can avoid the need for reallocation, if you know the final size of the vector, by calling reserve() to allocate enough memory before you start. Alternatively, there are containers like deque and list which don't move their elements as they grow, but which may be less efficient for other operations.

    As an aside, as noted in the comments, if the class is managing resources (which is implied by the presence of a destructor), you probably need to provide or delete the copy constructor and copy-assignment operator per the Rule of Three, and perhaps think about making it movable for efficiency.

    0 讨论(0)
提交回复
热议问题