c++c++11vectorc++17make-shared

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?


Solution

  • 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.