Does data in std :: vector in C ++ make a copy of the data?

I am wondering if creating a new std::vector (or calling its assign method) creates a copy of the data?

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? } 
+4
source share
5 answers

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 carrier
Erroap = 02-0304-231 ~ No carrier

+11
source

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

+9
source

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)); } 
+1
source

If you want your data to be moved, use std::swap_ranges , but you must first allocate memory:

 vector<T> v; v.reserve(std::distance(beg, end)); std::swap_ranges(beg, end, v.begin()); 
0
source

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.

0
source

Source: https://habr.com/ru/post/1315154/


All Articles