I am working with 2 libraries. One takes in and returns std::strings while the other uses std::vector<unsigned char>s.
It would be good if I could steal the underlying arrays from std::string and std::vector<unsigned char> and be able to move them into each other without the excessive copying.
ATM I use something like:
const unsigned char* raw_memory =
reinterpret_cast<const unsigned char*>(string_value.c_str()),
std::vector<unsigned char>(raw_memory, raw_memory + string_value.size();
And the other way:
std::string(
reinterpret_cast<const char*>(&vector_value[0]),
vector_value.size());
It’d be far better to be able to define a:
std::string move_into(std::vector<unsigned char>&&);
std::vector<unsigned char> move_into(std::string&&);
This is not possible.
The
vectorandstringclass do not provide way to steal from anything else thanvectororstringrespectively. They are not meant to exchange content.The problem issue is that
vectorandstringmay have widely different underlying representations. Typically in gcc for example,stringuse the oldish COW (Copy On Write) “optimization”, which is widely different from the typicalvectorrepresentation (usually just a triple of pointers/size_t attributes).If you are dealing with raw bytes, blame the library that decided to put them into
string, and refactor it if you can.Otherwise: copy. The
reinterpret_castshould not be necessary becausecharandunsigned charhave implicit casts between them (and nowcharis oftenunsignedby default).