J
John Salmon
I was under the impression that the following was always valid:
std::vector<T> v;
..
T *p = &(v[0]);
But I was recently told that care was needed in case the vector was
empty, i.e., when v.size() == 0.
I'm hoping that the above expression is fine, even if v is empty, but
that if you try to dereference p, you're in trouble.
If the above isn't ok, I'd have to write:
T *p = (v.size()!=0)? &(v[0]) : 0;
I took a look in the C++98 standard, and couldn't find anything to
confirm my hope. I see from Table 68 that the expression has the
"operational sematics" of
&(*(v.begin() + 0))
which sure *seems* like it might in turn be "operationally equivalent"
to v.begin(), which sure seems safe, even for an empty vector. But I
now feel myself to be on very thin ice.
So, can I write:
T *p = &(v[0]);
or do I have to write:
T *p = (v.size()!=0)? &(v[0]) : 0;
Thanks,
John Salmon
std::vector<T> v;
..
T *p = &(v[0]);
But I was recently told that care was needed in case the vector was
empty, i.e., when v.size() == 0.
I'm hoping that the above expression is fine, even if v is empty, but
that if you try to dereference p, you're in trouble.
If the above isn't ok, I'd have to write:
T *p = (v.size()!=0)? &(v[0]) : 0;
I took a look in the C++98 standard, and couldn't find anything to
confirm my hope. I see from Table 68 that the expression has the
"operational sematics" of
&(*(v.begin() + 0))
which sure *seems* like it might in turn be "operationally equivalent"
to v.begin(), which sure seems safe, even for an empty vector. But I
now feel myself to be on very thin ice.
So, can I write:
T *p = &(v[0]);
or do I have to write:
T *p = (v.size()!=0)? &(v[0]) : 0;
Thanks,
John Salmon