push_back vs emplace_back

后端 未结 7 2381
南旧
南旧 2020-11-22 03:41

I\'m a bit confused regarding the difference between push_back and emplace_back.

void emplace_back(Type&& _Val);
void push_         


        
7条回答
  •  野性不改
    2020-11-22 03:45

    emplace_back shouldn't take an argument of type vector::value_type, but instead variadic arguments that are forwarded to the constructor of the appended item.

    template  void emplace_back(Args&&... args); 
    

    It is possible to pass a value_type which will be forwarded to the copy constructor.

    Because it forwards the arguments, this means that if you don't have rvalue, this still means that the container will store a "copied" copy, not a moved copy.

     std::vector vec;
     vec.emplace_back(std::string("Hello")); // moves
     std::string s;
     vec.emplace_back(s); //copies
    

    But the above should be identical to what push_back does. It is probably rather meant for use cases like:

     std::vector > vec;
     vec.emplace_back(std::string("Hello"), std::string("world")); 
     // should end up invoking this constructor:
     //template pair(U&& x, V&& y);
     //without making any copies of the strings
    

提交回复
热议问题