C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Providing information about data structures to the compiler

From: Sebastian Wittmeier <wittmeier_at_[hidden]>
Date: Sat, 15 Mar 2025 19:55:51 +0100
To make it less surprising: The compiler doing the reserve() at the time of the first push_back().   push_back() kind of is allowed to allocate more memory. However, even that violates part of the contract:   https://en.cppreference.com/w/cpp/container/vector/push_back   If after the operation the new size() is greater than old capacity() a reallocation takes place, in which case all iterators (including the end() iterator) and all references to the elements are invalidated. Otherwise only the end() iterator is invalidated.   The iterators are invalidated prematurely.     So perhaps the compiler should only suggest to the programmer to consider reserve()         -----Ursprüngliche Nachricht----- Von:Tony V E via Std-Proposals <std-proposals_at_[hidden]> Gesendet:Sa 15.03.2025 19:38 Betreff:Re: [std-proposals] Providing information about data structures to the compiler An:std-proposals_at_[hidden]; CC:Tony V E <tvaneerd_at_[hidden]>; Stepanov originally hoped that something like concepts would eventually help with compiler optimizations.  ie if your type is Regular, then the compiler could make assumptions about copies, temporaries, etc.  Not sure what he was thinking wrt containers.  One that I recently noticed was this common anti-pattern:  for (int i = 0; i < some_fixed_value; i++)     vec.push_back(something());  the developer probably should have called reserve() before the loop, but didn't.  If compilers knew more about vector, they could do the reserve for you.  

Received on 2025-03-15 19:01:06