I am wondering if creating a new std::vector (or calling its assign method) creates a copy of the data?
std::vector
assign
For instance,
void fun(char *input) { std::vector<char> v(input, input+strlen(input)); // is it safe to assume that the data input points to was COPIED into v? }
Yes. Elements are always copied to or from STL containers. (At least until the semantics of the move is added in C ++ 0x)
EDIT: Here you can test to copy:
#include <vector> #include <iostream> class CopyChecker { public: CopyChecker() { std::cout << "Hey, look! A new copy checker!" << std::endl; } CopyChecker(const CopyChecker& other) { std::cout << "I'm the copy checker! No, I am! Wait, the" " two of us are the same!" << std::endl; } ~CopyChecker() { std::cout << "Erroap=02-0304-231~No Carrier" << std::endl; } }; int main() { std::vector<CopyChecker> doICopy; doICopy.push_back(CopyChecker()); }
The output should be:
Hey look! New copy machine!I am a checker! No me! Wait, the two of us! Erroap = 02-0304-231 ~ No carrierErroap = 02-0304-231 ~ No carrier
Elements are always copied to or from STL containers.
Although the element may be just a pointer, in which case the pointer is copied, but not the underlying data
About move semantics, here is how you could move content in C ++ 0x if you want:
void fun_move(char *input) { std::vector<char> v; auto len = strlen(input); v.reserve(len); std::move(input, input+len, std::back_inserter(v)); }
If you want your data to be moved, use std::swap_ranges , but you must first allocate memory:
std::swap_ranges
vector<T> v; v.reserve(std::distance(beg, end)); std::swap_ranges(beg, end, v.begin());
If you don't need the semantics of a copy of an object, you can instead create a vector of pointers to objects to copy only the pointer. However, then you must make sure that the pointers remain valid for the life of the container.
Source: https://habr.com/ru/post/1315154/More articles:Detect both left and right mouse clicks? - c #IEnumerable conversion for extension method - genericsDoes the clone method in C # (or in java) use the new operator inside? - javaCall sqlCommand in a loop to increase the execution time of each step - c #Development Conflict DevelopmentServerPort - mergejquery - how to select an element and all children except a specific child - jquery-selectorsDelphi - What happens to a non-running (but terminated) thread when an application exits? - multithreadingHow to get gettext work in IIS / PHP - phpMap iteration and mapping in jsp - jspThe basic structure of the database of intermediate additional models - sqlAll Articles