I weren't able to find that question, and it's an actual problem I'm facing.
I have a file loading utility that returns std::vector<unsigned char> containing whole file contents.
However, the processing function requires contiguos array of char (and that cannot be changed - it's a library function). Since the class that's using the processing function stores a copy of the data anyway, I want to store it as vector<char>. Here's the code that might be a bit more illustrative.
std::vector<unsigned char> LoadFile (std::string const& path);
class Processor {
std::vector<char> cache;
void _dataOperation(std::vector<char> const& data);
public:
void Process() {
if (cache.empty())
// here's the problem!
cache = LoadFile("file.txt");
_dataOperation(cache);
}
};
This code doesn't compile, because (obviously) there's no appropriate conversion. We can be sure, however, that the temporary vector will ocupy the same amount of memory (IOW sizeof(char) == sizeof(unsigned char))
The naive solution would be to iterate over the contents of a temporary and cast every character. I know that in normal case, the operator= (T&&) would be called.
In my situation it's safe to do reinterpreting conversion, because I am sure I am going to read ASCII characters only. Any other character would be caught in _dataOperation anyway.
So, my question is : how to properly and safely convert the temporary vector in a way that involves no copying?
If it isn't possible, I would prefer the safe way of copying rather than unsafe noncopying. I could also change LoadFile to return either vector<char> or vector<unsigned char>.
_dataOperation, you will probably be happier in the long run if you make it takevector<unsigned char>.unsigned char.reinterpret_cast<char *>(unsigned_vector.data())etc.