Does std::vector Copy Objects with push_back()?
After extensive analysis using Valgrind, it was concluded that std::vector performs a copy of objects inserted using push_back().
Internal Mechanism
Unlike the vector in C , which only operates on references, std::vector in C stores actual objects. This implies that each time push_back() is called, a copy of the inserted object is created and added to the vector's internal array.
Storage of Pointers
If you intend to store pointers within the vector, you should consider using std::vector
Smart Pointers
Smart pointers facilitate the management of object lifetime, thereby ensuring that the contained objects remain valid while referenced by the vector. They utilize the Resource Acquisition Is Initialization (RAII) idiom to automatically acquire and release resources.
In summary, std::vector::push_back() creates a copy of the inserted object, but utilizing smart pointers with std::vector
The above is the detailed content of Does `std::vector::push_back()` Create Copies of Objects?. For more information, please follow other related articles on the PHP Chinese website!