Vector.push_back rvalue and copy-elision

I push_back temporary object in vector , like this,

 vector<A> vec; vec.push_back(A("abc")); 

the compiler will use copy-elision to create a temporary A("abc") directly in vector , so A copy ctor will not start when a temporary object is clicked on vec .

+6
source share
2 answers

If you have a compiler that supports rvalue links, it will be moved to a vector, which is sometimes quite cheap.

An alternative to this is to directly create an object in a vector, which can be done using vec.emplace_back("abc"); . This only calls one constructor.

Both of these are C ++ 11 functions. Copying elision is not allowed here, so without these functions a copy will still be made.

However, if the copy constructor does not have observable side effects (which it should not have in any case), the smart compiler can still perform this optimization because the “as is” rule allows any optimization that leads to the same observed behavior. I do not know if any current compiler is working. If not, I doubt anyone will make an effort to add such optimization because rvalue links put an end to this need.

+5
source

In the general case, this cannot be done, it can be done here, since vector is a template, and the code can be embedded, which gives more information to the optimizer for this task and to eliminate some of the requirements of function calls.

In the general case, copying is performed by placing two objects in the same place in memory and having only two names for accessing one object. The problem in this case would be that one of the arguments must be located inside the vector (dynamically distributed in a certain position), and the other is the function argument, which can be associated with a call to a conditional position on the stack. If so, then the compiler will not be able to optimize the copy.

+1
source

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


All Articles