+ 2

Why value changes for bool but not for int using auto

Why value changes for bool but not for int when updated using auto Please refer code below : I just took copy of second element from int of vector using auto As auto does not give direct reference or const without explicitly using it with auto, i expected that change in iVal should not change element value in vector. This is fine and as per my expectation. This is not true for bool.... Why am I getting value changed for bool on smililar operation ? https://code.sololearn.com/cJR4Yk3bm3eZ/?ref=app

12th Jul 2022, 10:07 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Réponses
+ 2
The actual answer is that the = operator returns a bool reference, not a bool for vector<bool> ... it is a strange overload, but it is in the vector header. Reference: https://m.cplusplus.com/reference/vector/vector-bool/reference/ More detailed: https://en.cppreference.com/w/cpp/container/vector/operator%3D Ignore this below... didn't run the code before answering... ‐--------‐------‐---------------------------------- Hope my code explains it: https://code.sololearn.com/cpZ1klYcgZ54/?ref=app TL;DR: you need to think about ehat you actually assign. In C++ almost all types are pure value types. Except for pointers and references, where only a memory location gets assigned to the variable, so you can access the data they point to from multiple locations/variables. edit: I hope i even got your question right. i can't see anything unusual about the output. Pordon me if I got the question wrong!
12th Jul 2022, 11:23 AM
Erarnitox
Erarnitox - avatar
+ 1
Thanks Erarnitox ... I was confused why bool behaves differently than int Now got idea about template specialization for bool
12th Jul 2022, 11:42 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Ketan Lalcheta No worries, this is new to me as well, but it seems like vector<bool> is very optimized for space... still that overload does not make too much sense to me, as it is not intuitive, since all other types work differently. Glad I know about it now myself!
12th Jul 2022, 11:44 AM
Erarnitox
Erarnitox - avatar
+ 1
Yeah correct... that much optimization does not make sense at the cost of confusion...
12th Jul 2022, 11:46 AM
Ketan Lalcheta
Ketan Lalcheta - avatar