A general rule with STL containers is that they make copies of their contents. With C ++ 11, there are special ways to move elements to a container (for example, the emplace_back() function std::vector )., But in your example these elements are char objects, so you are still going to copy each of the size char objects.
Think of std::vector as a wrapper around a pointer to an array along with the length of the array. The closest equivalent to "casting a char * to std::vector<char> " is to replace a vector pointer and a length with a given pointer and length, but the length is specified (two possibilities are a pointer to one after the final element or size_t ). There is no standard member function std::vector that you can use to exchange your internal data with a given pointer and length.
This is for a good reason. std::vector implements property semantics for each element contained in it. Its base array is allocated by some distributor (the second parameter of the template), which by default is equal to std::allocator . If you are allowed to change internal members, you will need to make sure that the same set of heap allocation procedures has been used. In addition, your STL implementation will need to fix the method of storing the "length" of the vector, and not leave this detail undefined. In the OOP world, specifying more detailed information than necessary is generally dissatisfied, as this can lead to a higher connection.
But suppose such a member function exists for your STL implementation. In your example, you simply do not know how data was allocated, so you can inadvertently give the pointer std::vector pointer to a bunch of memory that was not allocated by the expected allocator. For example, data can be allocated with malloc , while a vector can free memory with delete . Using mismatched distribution and pivot routines results in Undefined Behavior. You may require that someFunction() only accept data allocated using a specific allocation procedure, but this indicates more details than necessary again.
I hope I made my case that the member function std::vector , which changes the internal data, is not a good idea. If you really need std::vector<char> from data and size , you should create it with:
std::vector<char> vec(data, data + size);
source share