Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ foreach-loop picks mutable begin() even

When writing

for(const auto& val: my_container)
  sum += val

Visual Studio picks the mutable version of begin(), is this by design or a bug?

As I using a copy on write container, this is quite a performance issue in my code.

like image 465
Viktor Sehr Avatar asked Apr 20 '26 23:04

Viktor Sehr


2 Answers

This is by design. The "foreach" loop doesn't look at the qualifiers or the reference qualifiers of the iteration variable when determining whether to treat my_container as const. Workaround is to add the const explicitly

const auto& my_container_const = my_container;
for(const auto& val: my_container_const)
   sum += val
like image 78
Johannes Schaub - litb Avatar answered Apr 23 '26 18:04

Johannes Schaub - litb


This is the expected behaviour a const_iterator isn't a const iterator and in any case begin returns const depending on the constness of the container not the variable that will store the return value.

like image 24
Motti Avatar answered Apr 23 '26 18:04

Motti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!