Efficiency of C++11 push_back() with std::move versus emplace_back() for already constructed objects

后端 未结 2 1254
北恋
北恋 2021-01-29 22:38

In C++11 emplace_back() is generally preferred (in terms of efficiency) to push_back() as it allows in-place construction, but is this still th

2条回答
  •  抹茶落季
    2021-01-29 23:26

    Let's see what the different calls that you provided do:

    1. emplace_back(mystring): This is an in-place construction of the new element with whatever argument you provided. Since you provided an lvalue, that in-place construction in fact is a copy-construction, i.e. this is the same as calling push_back(mystring)

    2. push_back(std::move(mystring)): This calls the move-insertion, which in the case of std::string is an in-place move-construction.

    3. emplace_back(std::move(mystring)): This is again an in-place construction with the arguments you provided. Since that argument is an rvalue, it calls the move-constructor of std::string, i.e. it is an in-place move-construction like in 2.

    In other words, if called with one argument of type T, be it an rvalue or lvalue, emplace_back and push_back are equivalent.

    However, for any other argument(s), emplace_back wins the race, for example with a char const* in a vector:

    1. emplace_back("foo") calls std::string(char const*) for in-place-construction.

    2. push_back("foo") first has to call std::string(char const*) for the implicit conversion needed to match the function's signature, and then a move-insertion like case 2. above. Therefore it is equivalent to push_back(string("foo"))

提交回复
热议问题