vendredi 30 septembre 2016

Is it specified in the C+11 standard that std::begin(Container&&) returns const_iterator?

Here's a link to relevant 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://ift.tt/2cQ9tYe

I ran into this behavior because of a declval<Container>() in a decltype expression with std::begin. Both gcc and clang return iterators which yield const references when dereferenced. It probably makes sense since r-value references usually bind to expiring objects that you don't want to mutate. However, I could not find any documentation on this to determine whether it's mandated by the standard. I couldn't find any relevant overloads of begin() or ref-qualified overloads of Container::begin().

Aucun commentaire:

Enregistrer un commentaire