emplace_back() does not behave as expected

后端 未结 2 1509
我在风中等你
我在风中等你 2020-12-18 18:09

I wrote a simple program to play around with in-place creation of objects inside standard library containers. This is what I wrote:

#include 
#         


        
相关标签:
2条回答
  • 2020-12-18 18:35

    The problem is that your vector is being resized as you add more elements, resulting in extra moves. If you reserve enough capacity at the start, you get the expected result:

       std::vector< AB > v;
       v.reserve(3);
       v.emplace_back(1);
       v.emplace_back(2);
       v.emplace_back(3);
    

    gives

    Object created.
    Object created.
    Object created.
    

    On gcc 4.8.2. Note that you can track the vector's growth in your original code by looking at v.capacity().

    0 讨论(0)
  • 2020-12-18 18:56

    The point of emplacement is to get rid of the COPY constructor calls. It's probably moving objects around due to resizing the vector when it's full. Moving an object is fine. Copying an object is expensive.

    0 讨论(0)
提交回复
热议问题