Is std::vector copying the objects with a push_back?

后端 未结 8 1752
夕颜
夕颜 2020-11-28 00:46

After a lot of investigations with valgrind, I\'ve made the conclusion that std::vector makes a copy of an object you want to push_back.

Is that really true ? A vect

8条回答
  •  一个人的身影
    2020-11-28 01:30

    Relevant in C++11 is the emplace family of member functions, which allow you to transfer ownership of objects by moving them into containers.

    The idiom of usage would look like

    std::vector objs;
    
    Object l_value_obj { /* initialize */ };
    // use object here...
    
    objs.emplace_back(std::move(l_value_obj));
    
    
    

    The move for the lvalue object is important as otherwise it would be forwarded as a reference or const reference and the move constructor would not be called.

    提交回复
    热议问题