Home > Backend Development > C++ > body text

Does std::vector Copy Objects on Push_back()?

Linda Hamilton
Release: 2024-11-04 04:44:01
Original
410 people have browsed it

Does std::vector Copy Objects on Push_back()?

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 or 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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!