push_back vs emplace_back

后端 未结 7 2438
南旧
南旧 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:56

    Specific use case for emplace_back: If you need to create a temporary object which will then be pushed into a container, use emplace_back instead of push_back. It will create the object in-place within the container.

    Notes:

    1. push_back in the above case will create a temporary object and move it into the container. However, in-place construction used for emplace_back would be more performant than constructing and then moving the object (which generally involves some copying).
    2. In general, you can use emplace_back instead of push_back in all the cases without much issue. (See exceptions)

提交回复
热议问题