Topic: Container and iterator member functions returning references
Author: Manuel Menezes de Sequeira <Manuel.Sequeira@iscte.pt>
Date: 2000/02/08 Raw View
The vector<bool> specialization defines operator[] to return an rvalue
of a reference class (__bit_reference, in egcs). Hence, the following
code is invalid:
void f(bool& b) {
...
}
int main() {
vector<bool> v(1);
f(v[0]);
}
>From the standard, I think
#include<vector>
void f(T& b) {
...
}
int main() {
vector<T> v(1);
f(v[0]);
}
is guaranteed to be correct if T != bool, since the default allocator is
being used and thus operator[] returns vector<T>::reference which is the
same as allocator<T>::reference, which in turn is the same as T&.
But
f(v.begin()[0]);
is not guaranteed to be correct, since a[n] returns a type convertible
to T, not mandatorily T& (Table 76). (However, Table 76 says a[n] has
the same "operational semantics" as *(a + n), which according to Table
74 returns T&.)
On the other hand
C c;
...
f(*c.begin());
is guaranteed to work, since *a returns T& (Table 74), for any type of
container C defined by the standard (except vector<bool>).
Am I right?
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html ]
Author: Manuel Menezes de Sequeira <Manuel.Sequeira@iscte.pt>
Date: 2000/02/09 Raw View
The vector<bool> specialization defines operator[] to return an rvalue
of a reference class (__bit_reference, in egcs). Hence, the following
code is invalid:
void f(bool& b) {
...
}
int main() {
vector<bool> v(1);
f(v[0]);
}
>From the standard, I think
#include<vector>
void f(T& b) {
...
}
int main() {
vector<T> v(1);
f(v[0]);
}
is guaranteed to be correct if T != bool, since the default allocator is
being used and thus operator[] returns vector<T>::reference which is the
same as allocator<T>::reference, which in turn is the same as T&.
But
f(v.begin()[0]);
is not guaranteed to be correct, since a[n] returns a type convertible
to T, not mandatorily T& (Table 76). (However, Table 76 says a[n] has
the same "operational semantics" as *(a + n), which according to Table
74 returns T&.)
On the other hand
C c;
...
f(*c.begin());
is guaranteed to work, since *a returns T& (Table 74), for any type of
container C defined by the standard (except vector<bool>).
Am I right?
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html ]