I want to write data from an std::v开发者_如何学编程ector<char>
to a socket, using the write
function, which has this prototype:
ssize_t write(int, const void *, size_t);
The second argument to this function must be a pointer to the first element in the std::vector<char>
. How can I get a pointer to this element?
I tried std::vector::front
but this returns a reference, while I need a pointer.
C++11 has vec.data()
which has the benefit that the call is valid even if the vector is empty.
&mv_vec[0]
or
&my_vec.front()
my_vec.empty() ? 0 : &my_vec.front()
If you would like an std::out_of_range
to be thrown if vector is empty, you could use
&my_vec.at(0)
&*my_vec.begin()
or
&mv_vec[0]
By taking the address of the first element, with &vec[0]
, as the standard (since C++03, I think) demands continous storage of std::vector
elements.
精彩评论