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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With