Is there a way I can directly send the std::string variable without
making a copy of it?
No, certainly not safely.
If you have control over the library, I'd suggest a slight refactor.
Either add:
template<typename CharT>
void WriteBinary(CharT const* buffer, size_t count);
Or:
template<typename FwdIter>
void WriteBinary(FwdIter begin, FwdIter end);
And then make your existing WriteBinary
and WriteString
call it:
void WriteBinary(std::vector<uint8_t> const& vec)
{ WriteBinary(&*vec.begin(), vec.size()); }
void WriteString(std::string const& s)
{ WriteBinary(&*s.begin(), s.size()); }
Or:
void WriteBinary(std::vector<uint8_t> const& vec)
{ WriteBinary(vec.begin(), vec.end()); }
void WriteString(std::string const& s)
{ WriteBinary(s.begin(), s.end()); }
Personally, I'd prefer the iterator based approach. It feels "cleaner".
(Note: for the pointer/size approach, you'd probably want to check for empty. Some implementations may assert if you deference the result of begin()
on an empty vector/string.)