Função membro .begin () e std :: begin ()
Chamando a função de membro.begin()
dostd::vector
estd::begin()
em rvalues resulta em saídas diferentes, como mostra o seguinte teste:
vector<int> a{ 1, 2, 3 };
vector<int>::iterator it1 = move(a).begin(); // OK
vector<int>::const_iterator it2 = move(a).begin(); // OK
vector<int>::iterator it3 = begin(move(a)); // Error!
vector<int>::const_iterator it4 = begin(move(a)); // OK
Aqui está o meu entendimento:std::begin()
chamadasconst&
sobrecarga (já que falta&&
sobrecarga) e, portanto, retorna umaconst_iterator
objeto. Portanto, o valor retornado pode ser atribuído aconst_iterator
mas nãoiterator.
std::begin()
não tem uma sobrecarga de rvalue?Apenas uma nota que eu useimove(a)
demonstrar chamada.begin()
estd::begin()
em rvalues. Obviamente, ele pode ser substituído por qualquer objeto rvalue para o qual.begin()
estd::begin()
estão bem definidos.
Editar: Aqui está o exemplo real mostrando onde eu encontrei esse problema. Simplifiquei muito apenas para transmitir a ideia de ondestd::begin()
é chamado em um rvalue. Então, desderow_matrix
é uma classe proxy, não deve haver nenhum problema ao chamarbegin
eend
em rvalues, pois o objeto subjacente é idêntico.
class matrix_row;
class row_iterator;
class matrix {
public:
matrix_row row(int i);
// other members
};
class matrix_row { // <- proxy class representing a row of matrix
public:
row_iterator begin();
row_iterator end();
// other members
private:
int row_;
matrix& matrix_;
};
class row_iterator {
// defined everything needed to qualify as a valid iterator
};
matrix m(3,4);
for(auto x = m.row(1).begin(); x != m.row(1).end(); ++x) {
*x /=2; // OK
}
for(auto x = begin(m.row(1)); x != end(m.row(1)); ++x) {
*x /= 2; // Error
}