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

后端 未结 2 1260
北恋
北恋 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:34

    The emplace_back gets a list of rvalue references and tries to construct a container element direct in place. You can call emplace_back with all types which the container element constructors supports. When call emplace_back for parameters which are not rvalue references, it 'falls back' to normal references and at least the copy constructor ist called when the parameter and the container elements are of the same type. In your case 'myvector.emplace_back(mystring)' should make a copy of the string becaus the compiler could not know that the parameter myvector is movable. So insert the std::move what gives you the desired benefit. The push_back should work as well as emplace_back for already constructed elements.

提交回复
热议问题