std ::在std :: string和std :: vector之间移动(< unsigned char> [英] std::move between std::string and std::vector<unsigned char>

查看:179
本文介绍了std ::在std :: string和std :: vector之间移动(< unsigned char>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用2个库.一个接收并返回std::string s,而另一个使用std::vector<unsigned char> s.

I am working with 2 libraries. One takes in and returns std::strings while the other uses std::vector<unsigned char>s.

如果我可以从std::stringstd::vector<unsigned char>窃取基础数组,并能够将它们相互移动而又不过度复制,那将是一个很好的选择.

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我使用类似的东西:

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();

另一种方式:

std::string(
    reinterpret_cast<const char*>(&vector_value[0]),
    vector_value.size());

最好能够定义一个:

std::string move_into(std::vector<unsigned char>&&);
std::vector<unsigned char> move_into(std::string&&);

推荐答案

这是不可能的.

除了vectorstring 以外,vectorstring类没有提供从其他任何东西窃取的方法.它们无意交换内容.

The vector and string class do not provide way to steal from anything else than vector or string respectively. They are not meant to exchange content.

问题在于,vectorstring可能具有广泛不同的基础表示形式.例如,通常在gcc中,string使用较旧的COW(写时复制)优化",它与典型的vector表示形式(通常只有指针/size_t属性的三倍)有很大不同.

The problem issue is that vector and string may have widely different underlying representations. Typically in gcc for example, string use the oldish COW (Copy On Write) "optimization", which is widely different from the typical vector representation (usually just a triple of pointers/size_t attributes).

如果要处理原始字节,请怪罪决定将其放入string的库,并在可能的情况下对其进行重构.

If you are dealing with raw bytes, blame the library that decided to put them into string, and refactor it if you can.

否则:复制. reinterpret_cast不必要,因为charunsigned char之间具有隐式强制转换(现在char默认情况下通常为unsigned).

Otherwise: copy. The reinterpret_cast should not be necessary because char and unsigned char have implicit casts between them (and now char is often unsigned by default).

这篇关于std ::在std :: string和std :: vector之间移动(&lt; unsigned char&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆