Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using make_shared with emplace_back and push_back - any difference?

some_vector.push_back(make_shared<ClassName>());
some_vector.emplace_back(make_shared<ClassName>());

I want to check that my understanding is correct that for make_shared and in general for all other functions that returns an object those two calls are identical. Here make_shared will create a new shared_ptr, and then this pointer will be moved into the container both in push_back and emplace_back. Is this correct, or will there be some difference?

like image 650
Johy Avatar asked Nov 01 '25 18:11

Johy


1 Answers

vector<T>::push_back has a T&& overload, which does the same as the vector<T>::emplace_back T&& version.

The difference is that emplace_back will perfect-forward any set of arguments to the T's constructor, while push_back only takes T&& or T const&. When you actually pass a T&& or T const& the standard specification of their behaviour is the same.

like image 71
Yakk - Adam Nevraumont Avatar answered Nov 04 '25 09:11

Yakk - Adam Nevraumont



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!