I have a std::vector of bytes (char), I’d like to do the equivalent of just “C-style casting” this vector to a vector which is of type wchar_t.
Obviously, what I really have to do is to copy the data, but the thing here is that I already have an UTF-16 byte stream on the left side, I just wanna move that over to the wchar_t vector so that I can use it. Ideally, I’d like to just swap the buffer, but I’m not sure how to do that in safe manner…
What’s the C++ way of doing an as efficient as safe conversion copy operation allows?
NOTE:
I do store my UTF-16 strings as std::wstring or std::vector<wchar_t> but I have this memory buffer that I happen to know is UTF-16, and I need to copy it, somehow…
The most efficient (and sanest) way to do it is to not do it. Let your
vector<char>own the data buffer, and simply create a pair ofwchar_tpointers to use as iterators pointing into the vector.Now you have an iterator pair that’ll work just fine with all the standard library algorithms.
And you didn’t have to copy a single byte. 🙂
(Disclaimer: I’m assuming that the vector’s size is divisible by
sizeof(wchar_t). Otherwise you’ll have to adjust thelastpointer)