Home >Backend Development >C++ >Does std::vector Copy Objects on Push_back()?

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-04 04:44:01471browse

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!

Statement:
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