Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying std::vector of primitive types behavior

Background:

When copying a std::vector using its copy constructor or copy assignment like this:

std::vector<T> v1{T(),T(),T()};
std::vector<T> v2 = v1;

a deep copy happens.

Is it guaranteed by the standard that the copy constructor of T will be triggered for each element? In other words no memcpy (or something similar) will be called. (Correct me if I am wrong).

Question:

On the other hand, is it guaranteed by the standard that it would call memcpy (or something similar) on primitive types (for performance issues)?

like image 620
Humam Helfawi Avatar asked Dec 20 '25 19:12

Humam Helfawi


2 Answers

Yes, T's copy constructor must be called. If the copy constructor is trivial, it's effect is the exact same as that of memcpy, so an implementation is fine to use the latter to implement that copy constructor. From there on, the implementation may decide to use memcpy to implement the copy constructor of vector. That decision makes use of the as-if rule: The program's observable behavior remains unchanged, hence we need not actually perform all the copy constructor calls.

On the other hand, does it guaranteed by the standard that it would call memcpy (or something similar) on primitive types (for performance issues)?

No, because how a copy constructor is actually implemented is an implementation detail. The standard merely specifies a program's (observable) behavior, and it does that using the notion of copy constructors etc. Optimization is nothing an abstract standard document should worry about, but your vendor. In fact, restraining the definitions of such functions would either incur a huge deficit in optimization, or be outright ignored due to the aforementioned as-if rule.

like image 176
Columbo Avatar answered Dec 22 '25 12:12

Columbo


The exact code generated for copy construction of primitive types is a quality of implementation issue. In other words, the standard will not guarantee anything of the sort - at best, it will specify the algorithmic complexity of the operation, in this case copying of the vector can be inferred as O(n).

With modern C++ compilers on a reasonable optimization setting, you can count on copy construction of POD classes being implemented in-line, as efficiently as a constant-size memcpy. Doing anything else would incur serious penalties with typical use cases, such as STL containers of pointers.

like image 25
user4815162342 Avatar answered Dec 22 '25 10:12

user4815162342



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!