How to convert std::vector<unsigned char> to vector<char> without copying?

两盒软妹~` 提交于 2019-12-03 23:21:00

In C++11, [basic.lval]p10 says,

If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:

  • ...
  • a char or unsigned char type.

(the exact location may be different in other versions of C++, but the meaning is the same.)

That means that you can take a vector<unsigned char> cache and access its contents using the range [reinterpret_cast<char*>(cache.data()), reinterpret_cast<char*>(cache.data()) + cache.size()). (@Kerrek SB mentioned this.)

If you store a vector<unsigned char> in Processor to match the return type of LoadFile, and _dataOperation() actually takes an array of char (meaning a const char* and a size), then you can cast when you're passing the argument to _dataOperation()

However, if _dataOperation() takes a vector<char> specifically and you store a vector<unsigned char> cache, then you cannot pass it reinterpret_cast<vector<char>&>(cache). (i.e. @André Puel is totally wrong. Do not listen to him.) That violates the aliasing rules, and the compiler will attempt to anger your customers at 2am. (And if this version of your compiler doesn't manage it, the next version will keep trying.)

One option is, as you mentioned, to template LoadFile() and have it return (or fill in) a vector of the type you want. Another is to copy the result, for which the concise version is again the reinterpret_cast of the source vector's .data(). [basic.fundamental]p1 mentions that "For character types, all bits of the object representation participate in the value representation.", meaning that you're not going to lose data with that reinterpret_cast. I don't see a firm guarantee that no bit pattern of an unsigned char can cause a trap if reinterpret_cast'ed to char, but I don't know of any modern hardware or compilers that do it.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!