Home > Backend Development > C++ > Does `std::vector::push_back()` Copy Objects?

Does `std::vector::push_back()` Copy Objects?

DDD
Release: 2024-11-03 18:51:29
Original
659 people have browsed it

Does `std::vector::push_back()` Copy Objects?

Does std::vector Copy Objects with push_back?

After conducting extensive investigations using Valgrind, it has been suggested that std::vector creates a copy of any object pushed back into the vector. Is this assertion accurate? Can a vector not maintain a reference or pointer to an object without copying it?

Answer:

Yes, std::vector::push_back() indeed creates a copy of the supplied argument and adds it to the vector. If you intend to store pointers to objects within the vector, employ std::vector rather than std::vector.

However, you must guarantee that the objects referenced by the pointers remain valid while the vector maintains a reference to them. Smart pointers based on the RAII idiom offer a solution to this problem.

The above is the detailed content of Does `std::vector::push_back()` Copy Objects?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template