Skip to content

std::vector::reserve and reducing memory reallocations initializer lists and emplace_back #539

Open

Description

@Carmelo908

Channel

C++Weekly

Topics

It's said that you shouldn't add elements to a std::vector while iterating it, because it may cause a reallocation and this will cause all iterators to be left dangling. But what if we use std::vector::reserve before creating those iterators to avoid reallocation? what is the frequency with which std::vector has to reallocate itself when adding new elements? If I know my final size before hand, how much of a performance difference will make to call vector::reserve before my operations?

Length

I don't think this would take more than 10 minutes to explain

Activity

  1. LB-- commented on Mar 17, 2026

    @LB--

    There's not much to explain, the standard guarantees that no reallocations will occur if you stay within the reserve size you requested, so if you reserve the final size in advance there will be no reallocations and no iterator invalidations.

  2. Carmelo908 commented on Mar 17, 2026

    @Carmelo908
    Author

    Well, I find it very strange that I don't see anyone talking about reserve (which is also in std::string by the way)

  3. changed the title [-]std::vector::reserve and reducing memory reallocations[/-] [+]std::vector::reserve and reducing memory reallocations initializer lists and emplace_back[/+] on Oct 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions