I have a function that returns a std::vector<std::byte>
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.
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:
no suitable user-defined conversion from "std::vector<std::byte, std::allocatorstd::byte>" to "std::vector<char,std::allocator>" exists
Is this at all possible using C++? I think there are real use cases where one would want to do this
std::byte
s, hence you can't move them as new types. moving means transferring the ownership i.e the elements themselves will be moved, so If you can change the type of some object (without copying), you can do what you want. – Utasstd::vector<std::byte> bytevec
. This vector only contains character data (i.e. data which can be represented as char). I would like to be able to do something likestd::vector<char> charvec = std::move(bytevec)
so that the underlying buffer with the data is transferred from bytevec to charvec without actually copying the data. Of course the compiler complains because std::byte cannot be implicitly converted to char, so I was wondering if there is a way to 'cast' it while using std::move? – Ammonalstd::vector
like type that has the ability to adopt external memory. Or consider std::span. – Pironivector<byte>
and provides achar
(oruint8_t
) interface that deals with the casting back and forth? I think that's the route I'd take. – Middletonvector<T>
doesn't store memory; it stores an array ofT
s. It is reasonable to allow avector<T>
instance to adopt the storage from anothervector<T>
instance. It makes far less sense for it to be able to adopt the "memory" of some unrelated typevector<U>
, since that is an array ofU
s, which is not an array ofT
s. – HeroicU
s is not an array ofT
s. But the strict aliasing rule makes that a bit more complicated than simplyis_same_type_v<remove_const<T>, remove_const<U>>
, because e.g. signed and unsigned variations of the same type are guaranteed to be representation-compatible and valid for aliasing, so any time you have anunsigned[N]
you do in fact also have anint[N]
and vice versa. Here the question involves compatibility betweenstd::byte
andchar
. – Subantarcticstd::byte
or so). – Andaman