Search code examples
c++vectorpush-backcopy-elision

push_back copy objects even for temps although stating otherwise in it's definition?


one of push_back definition is

  push_back(const value_type& __x)

so Having my_vector2.push_back( obj ); will result in passing object obj by reference( No copy during passing object) still it call the copy constructor in the body of push_back somewhere so why not just pass it by value ie;

  push_back(const value_type  __x)

and make behavior of it understandable from just reading the function prototype. I dont know if copy elision will step in since it's supposed for return values only and constructors dont return anything. So would in any case copy-elision step in during passing of objects to functions or methods in any way or is it for return values only. I mean elision a copy of an object passed by value to a function(push_back) or whatever so we we have to make a copy in the body of push_back?

second thing that's Even more confusing it also take a copy of a Temporary and same behavior as above it take it by rvalue reference push_back(value_type&& __x) so why take a copy of an already temporary object. I mean I dont need it (it's a temp) I know there is point a miss here but what is it.


Solution

  • push_back predates move semantics, so the best std::vector can do is copy. While it could have changed with C++11, this would also be a change of behavior, which might break code in some cases (weird cases, but still valid ones).

    If you want to avoid copies when dealing with temporaries, then you actually want emplace_back, which does exactly what you're describing. It will construct the object in place in the vector's storage, so your overhead if passing a temporary is a move ctor.