分配 std::vector到 std::vector无需复制内存

分配 std::vector<std::byte>到 std::vector<char>无需复制内存

问题描述:

我有一个返回 std::vector<:byte>

我知道 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<:byte std::allocatorsstd::byte>"的用户定义转换到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);

这里有现场演示