乐闻世界logo
搜索文章和话题

Is std::vector copying the objects with a push_back?

1个答案

1

Yes, the push_back method of std::vector typically involves copying objects. When adding elements to std::vector, the push_back method copies the provided element to the container's internal storage. This process typically involves calling the copy constructor or move constructor of the element type (if applicable).

Example:

Suppose there is a simple class Widget:

cpp
class Widget { public: Widget() { std::cout << "Default constructor" << std::endl; } Widget(const Widget&) { std::cout << "Copy constructor" << std::endl; } Widget(Widget&&) noexcept { std::cout << "Move constructor" << std::endl; } ~Widget() {} };

When adding elements to std::vector<Widget>:

cpp
int main() { std::vector<Widget> v; Widget w; std::cout << "Adding to vector:" << std::endl; v.push_back(w); // This will call the copy constructor of Widget v.push_back(std::move(w)); // This will call the move constructor of Widget return 0; }

In the above code:

  1. Creating an instance w of the Widget class will call the default constructor.
  2. Using push_back(w) to add w to vector v will call the copy constructor.
  3. Using push_back(std::move(w)) to add w to vector v will call the move constructor.

Optimization:

Since C++11, if the type supports move semantics, std::vector will prefer using the move constructor to reduce the cost of copying. Additionally, if you know you will be adding many elements, using the reserve method to pre-allocate sufficient memory can avoid reallocations and copying existing elements when adding new elements.

In summary, the push_back method of std::vector does involve copying objects, but the specific behavior (whether it is a copy or a move) depends on the element type and whether move semantics are enabled.

2024年6月29日 12:07 回复

你的答案