C++ Logo

std-proposals

Advanced search

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

From: Filip <fph2137_at_[hidden]>
Date: Sun, 16 Mar 2025 11:13:21 +0100
I would add to the discussion a possible improvement:
[[foreign]] void *

That could tell the compiler that no optimization could be done since the class does not own the pointer.

But with regards to the for loop anti pattern mentioned before maybe other attributes could be added like:
[[require use of(<name of function>]]
That could throw a warning that this functionality is best paired by other function.

Although I would like to use something like ‘vec.push_back_n(maxNum, valueToPush);’
That could simply have the loop with reserve beforehand.

Cheers, Filip

Wiadomość napisana przez Sebastian Wittmeier via Std-Proposals <std-proposals_at_[hidden]> w dniu 15 mar 2025, o godz. 20:01:

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

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.

 

--
Std-Proposals mailing list
Std-Proposals_at_[hidden]
https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2025-03-16 10:13:37