Here is a link to the corresponding code:
#include <iostream> #include <string> #include <vector> #include <type_traits> int main() { std::vector<int> v{1, 2, 3, 4, 5}; auto iter = begin(std::move(v)); if(std::is_const<typename std::remove_reference<decltype(*iter)>::type>::value) std::cout<<"is const\n"; return 0; }
http://coliru.stacked-crooked.com/a/253c6373befe8e50
I came across this behavior due to declval<Container>() in the decltype with std::begin . Both gcc and clang return iterators that return constant references when dereferencing. This probably makes sense, since references to r-values ββare usually associated with obsolete objects that you do not want to modify. However, I could not find any documentation on this issue to determine if it is mandatory in accordance with the standard. I could not find any matching begin() overloads or Container::begin() overridden overloads.
Update: The answers clarified what is happening, but the interactions can be subtle, as shown below:
#include <iostream> #include <string> #include <vector> #include <type_traits> int main() { if(std::is_const<typename std::remove_reference<decltype(*begin(std::declval<std::vector<std::string>>()))>::type>::value) std::cout<<"(a) is const\n"; if(!std::is_const<typename std::remove_reference<decltype(*std::declval<std::vector<std::string>>().begin())>::type>::value) std::cout<<"(b) is not const\n"; if(!std::is_const<typename std::remove_reference<decltype(*begin(std::declval<std::vector<std::string>&>()))>::type>::value) std::cout<<"(c) is not const\n"; return 0; }
http://coliru.stacked-crooked.com/a/15c17b288f8d69bd
Naively, you do not expect different results for (a) and (b) when :: begin is defined only in terms of calling vector :: begin. However, the lack of overloads of std :: begin, which take a non-constant reference to the r-value and return an iterator (or overloads with the qualification vector :: begin, which return const_iterator), causes exactly this.
source share