push_back or emplace_back with std::make_unique

时间秒杀一切 提交于 2019-11-30 17:29:21

It doesn't make a difference as far as construction of the new object is concerned; you already have a unique_ptr<Foo> prvalue (the result of the call to make_unique) so both push_back and emplace_back will call the unique_ptr move constructor when constructing the element to be appended to the vector.

If your use case involves accessing the newly constructed element after insertion, then emplace_back is more convenient since C++17 because it returns a reference to the element. So instead of

my_vector.push_back(std::make_unique<Foo>("constructor", "args"));
my_vector.back().do_stuff();

you can write

my_vector.emplace_back(std::make_unique<Foo>("constructor", "args")).do_stuff();
Yakk - Adam Nevraumont

Clearly

template<class T, class A, class...Args>
void push_unique( std::vector<std::unique_ptr<T>,A>& v, Args&&...args ) {
  v.push_back( std::make_unique<T>(std::forward<Args>(args)...) );
}

is the best option:

push_unique(my_vector,"constructor", "args");

sadly this is prefix notation: (operator, container, arguments...) vs infix (container operator arguments...).

If only there was a way to make it infix, like extension methods or named operators.

Because that would be cool.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!