According to the draft standard (23.3.6.4 vector data), data() points to the underlying array and [data(), data() + size())
must be a valid range:
T* data() noexcept;
const T* data() const noexcept;
1 Returns: A pointer such that [data(),data() + size()) is a valid range. For a non-empty vector,
data() == &front().
2 Complexity: Constant time
But what if the vector is empty? When I construct a zero-size vector:
#include <vector>
#include <iostream>
int main() {
const int NUM = 0*10;
std::vector< double > v( NUM, 0.0 );
std::cerr << "V : "<< v.data() << std::endl;
}
MSVC 2010 returns null, but on Linux (with GCC 4.2.1 and Intel 12.1) I get a non-null address.
Is vector::data()
allowed to or should it return null? Could an implementation, for example, do a default-size initial allocation and return a (non-null) pointer to it?
Edit: Several answers focus on the validity of an empty-range. I fully agree there.
I would really like to see a good reference or explanation for: Is it allowed to, must it return null or may it also return non-null?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…