Does std::vector Copy Objects on push_back()?
Following investigations using Valgrind, a user concluded that std::vector creates copies of objects when performing push_back(). This raises the question:
Can't std::vector Store References or Pointers Without Copying?
Unfortunately, the answer is affirmative. std::vector::push_back(), as designed, creates a copy of the object passed as an argument and stores it within the vector.
Alternatives to Avoid Copying:
If the desired behavior is to store pointers or references instead of copies, consider utilizing a std::vector
Caution:
When employing pointers or references, ensure that the referenced objects remain valid throughout the lifetime of the vector. Employing smart pointers that utilize Resource Acquisition Is Initialization (RAII) can effectively address this issue.
The above is the detailed content of Does std::vector Copy Objects on Push_back()?. For more information, please follow other related articles on the PHP Chinese website!