分配 std::vector<std::byte>到 std::vector<char>无需复制内存 [英] Assign std::vector<std::byte> to std::vector<char> WITHOUT copying memory
问题描述
我有一个返回 std::vector
我知道 std::byte
既不是字符类型也不是整数类型,并且只能通过类型转换才能将其转换为 char.到目前为止一切顺利.
I am aware that std::byte
is not a character type nor an integral type, and that converting it to char is only possible through a typecast. So far so good.
所以我想(在我知道向量只包含字符数据的情况下)从 std::vector<std::byte> 转移底层缓冲区的所有权.
到 std::vector
使用 std::move
,以避免复制整个底层缓冲区.
So I would like (in cases where I know that the vector only contains character data) to transfer ownership of the underlying buffer from the std::vector<std::byte>
to a std::vector<char>
using std::move
, so as to avoid copying the entire underlying buffer.
当我尝试这样做时,我收到此错误:
When I try doing this, I get this error:
没有合适的从std::vector
no suitable user-defined conversion from "std::vector<std::byte, std::allocatorstd::byte>" to "std::vector<char,std::allocator>" exists
这完全可能使用 C++ 吗?我认为在某些实际用例中人们会想要这样做
Is this at all possible using C++? I think there are real use cases where one would want to do this
推荐答案
您可以通过强制转换来实现这一点,如下所示.这是合法的,因为转换是对 char
引用(如果转换为任何其他类型,它将是 UB)但是,至少使用 gcc,您仍然必须使用 -fno- 编译它严格别名
使编译器警告静音.无论如何,这是演员表:
You can achieve this with a cast, as shown below. This is legal because the cast is to a char
reference (if casting to any other type it would be UB) but, with gcc at least, you still have to compile it with -fno-strict-aliasing
to silence the compiler warning. Anyway, here's the cast:
std::vector <char> char_vector = reinterpret_cast <std::vector <char> &&> (byte_vector);
这篇关于分配 std::vector<std::byte>到 std::vector<char>无需复制内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!